Flutter double to Time in hours - flutter

I'm trying to convert a double value (e.g. 9.5) to a corresponding hour/minute value (e.g. 9.30). I also want to perform calculations using this value, but handle it like a time value (e.g. adding 23 and 2 should result in 1 as the hours should wrap around at 24 hours).
I already tried to convert the value to DateTime, but it says "invalid date format".

This should do it
void main() {
print(getTimeStringFromDouble(9.5)); // 9:30
print(getTimeStringFromDouble(25.0)); // 1:0
}
String getTimeStringFromDouble(double value) {
if (value < 0) return 'Invalid Value';
int flooredValue = value.floor();
double decimalValue = value - flooredValue;
String hourValue = getHourString(flooredValue);
String minuteString = getMinuteString(decimalValue);
return '$hourValue:$minuteString';
}
String getMinuteString(double decimalValue) {
return '${(decimalValue * 60).toInt()}'.padLeft(2, '0');
}
String getHourString(int flooredValue) {
return '${flooredValue % 24}'.padLeft(2, '0');
}

Related

How to hide decimal value when it is = 0

I am currently trying to render the price value of products using a widget in Flutter.
To do so, I pass the state and render it in the argument from the corresponding widget.
What I need to achieve is to hide the 2 decimals of my Double type priceValue and show them if they are != to 0.
Like so, if state.priceValue = 12.00 $ => should show 12
if state.priceValue = 12.30 $ => should show 12.30
String removeZero(double money) {
var response = money.toString();
if (money.toString().split(".").length > 0) {
var decmialPoint = money.toString().split(".")[1];
if (decmialPoint == "0") {
response = response.split(".0").join("");
}
if (decmialPoint == "00") {
response = response.split(".00").join("");
}
}
return response;
}
Edit: I added to check if the string contains a decimal point or not to avoid index out of bounds issue
Try this:
String price = "12.00$"
print(price.replaceAll(".00", ""));
Or refer to this: How to remove trailing zeros using Dart
double num = 12.50; // 12.5
double num2 = 12.0; // 12
double num3 = 1000; // 1000
RegExp regex = RegExp(r'([.]*0)(?!.*\d)');
String s = num.toString().replaceAll(regex, '');
But the second option will remove all trailing zeros so 12.30 will be 12.3 instead
Hello you could use an extension like that:
extension myExtension on double{
String get toStringV2{
final intPart = truncate();
if(this-intPart ==0){
return '$intPart';
}else{
return '$this';
}
}
}
To use the extension:
void main() {
double numberWithDecimals = 10.8;
double numberWithoutDecimals = 10.00;
//print
print(numberWithDecimals.toStringV2);
print(numberWithoutDecimals.toStringV2);
}

Uncaught Error: TypeError: 100: type 'JSInt' is not a subtype of type 'String'

void main() {
String num = "50";
int quantity = 2;
num = (int.parse(num) * quantity) as String;
print("num is "+num);
}
This is giving me error
Actually i want to convert a string to numerical value and perform calculations and update the string back with the updated value.
// Assume the intial value of
// item.quantity = 1, item.cost = 20
-----------------------------------------------------------------
item.quantity++;
item.cost = (int.parse(item.cost) * item.quantity) as String;
-----------------------------------------------------------------
====================================================
expected result item.cost = 40
generated result is 2020
====================================================
By using toString you create a new String value. By casting as T you tell the compiler that an unknown value you want as T value.
void main() {
String numer = "50";
int quantity = 2;
numer = (num.parse(numer) * quantity).toString();
print("sum is $numer"); // sum is 100
}
Note: avoid use names which is reserved by system to avoid conflict.

flutter:: Is it possible to change the timezone of a datetime?

I want to represent the time the file was saved as a string. The time in my country is 9 hours ahead of utc time. How can I change the current utc time to 9 hours faster?
String _getTime({required String filePath}) {
String fromPath = filePath.substring(
filePath.lastIndexOf('/') + 1, filePath.lastIndexOf('.'));
if (fromPath.startsWith("1", 0)) {
DateTime dateTime =
DateTime.fromMillisecondsSinceEpoch(int.parse(fromPath));
var dateLocal = dateTime.toLocal();
print(dateLocal);
print(dateTime);
int year = dateLocal.year;
int month = dateLocal.month;
int day = dateLocal.day;
int hour = dateLocal.hour;
int min = dateLocal.minute;
String dato = '$year-$month-$day--$hour:$min';
return dato;
} else {
return "No Date";
}
}
Use this package ---->>>>> https://pub.dev/packages/flutter_native_timezone
Add the package dependencies to your project, import the package into the file you're working in and write the code below to get your currenTimeZone
final String currentTimeZone = await FlutterNativeTimezone.getLocalTimezone();
debugPrint(currentTimeZone);

Convert seconds to mm:ss in dart

I want to convert seconds to minutes and seconds in HH:SS format but my logic don't give me what I want.
static double toMin (var value){
return (value/60);
}
I also want to be able to add the remainder to the minutes value because sometimes my division gives me a seconds value more that 60 which is not accurate
The Duration class can do most of the work for you.
var minutes = Duration(seconds: seconds).inMinutes;
You could generate a String in a mm:ss format by doing:
String formatDuration(int totalSeconds) {
final duration = Duration(seconds: totalSeconds);
final minutes = duration.inMinutes;
final seconds = totalSeconds % 60;
final minutesString = '$minutes'.padLeft(2, '0');
final secondsString = '$seconds'.padLeft(2, '0');
return '$minutesString:$secondsString';
}
That said, I recommend against using a mm:ss format since, without context, it's unclear whether "12:34" represents 12 minutes, 34 seconds or 12 hours, 34 minutes. I suggest instead using 12m34s, which is unambiguous.
you can do something like this:
void main() {
print(toMMSS(100));
}
String toMMSS(int value) =>
'${formatDecimal(value ~/ 60)}:${formatDecimal(value % 60)}';
String formatDecimal(num value) => '$value'.padLeft(2, '0');
or
String toMMSS(int value) =>
'${(value ~/ 60).toString().padLeft(2, '0')}:${(value % 60).toString().padLeft(2, '0')}';
also, you can create an extension on int:
extension DateTimeExtension on int {
String get toMMSS =>
'${(this ~/ 60).toString().padLeft(2, '0')}:${(this % 60).toString().padLeft(2, '0')}';
}
usage:
print(342.toMMSS);
You could try the solution below, this is how I'm doing it:
String formatHHMMSS(int seconds) {
if (seconds != null && seconds != 0) {
int hours = (seconds / 3600).truncate();
seconds = (seconds % 3600).truncate();
int minutes = (seconds / 60).truncate();
String hoursStr = (hours).toString().padLeft(2, '0');
String minutesStr = (minutes).toString().padLeft(2, '0');
String secondsStr = (seconds % 60).toString().padLeft(2, '0');
if (hours == 0) {
return "$minutesStr:$secondsStr";
}
return "$hoursStr:$minutesStr:$secondsStr";
} else {
return "";
}
}
static String formatYMDHMSBySeconds(int milliseconds) {
if (milliseconds == null) {
return '';
}
DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(milliseconds);
return DateFormat("yyyy-MM-dd HH:mm:ss").format(dateTime);
}

How to format an integer to ss:m

I'm trying to get the following format from an int: ss:m (s = seconds, m = milliseconds) from a countdown timer. If there are minutes, the format should be mm:ss:m.
Here's my code:
final int currentTime = 100; // 10 seconds
final Duration duration = Duration(milliseconds: 100);
Timer.periodic(duration, (Timer _timer) {
if (currentTime <= 0) {
_timer.cancel();
} else {
currentTime--;
print(currentTime);
}
});
I tried adding currentTime to a Duration as milliseconds but it didn't give me the desired results. What am I doing wrong and how can I get it to the correct format?
I have used the below method the get it in hh:mm:ss / mm:ss format, you can tweak to get in s:mm
String getTime(int milis) {
Duration position = Duration(milliseconds: milis);
String twoDigits(int n) {
if (n >= 10) return "$n";
return "0$n";
}
String twoDigitMinutes = twoDigits(position.inMinutes.remainder(60));
String twoDigitSeconds = twoDigits(position.inSeconds.remainder(60));
String time;
if (twoDigits(position.inHours) == "00") {
time = "$twoDigitMinutes:$twoDigitSeconds";
} else {
time = "${twoDigits(position.inHours)}:$twoDigitMinutes:$twoDigitSeconds";
}
return time;
}
try Duration.toString() it'll give you a string formatted in your requirement
more precisely
Duration(milliseconds:currentTime).toString()
and 100 millis is not 10 seconds
10000 millis is 10 seconds