Home > Enterprise >  Flutter/Dart: parse Duration from double (hours)
Flutter/Dart: parse Duration from double (hours)

Time:12-23

I have a double value which is a number of hours that I need to convert it to Duration. Suppose I have a function prototype like this

Duration parseDurationFromDouble(double d) {
    // parse the double
    return parsedDuration;
}

and

2.5 as my duration stored in double, then the function should return, like this:

Duration(hours: 2, minutes: 30)

How to do this in Dart? Can I convert it directly? Or should I done this through String interpolation?

Thanks in advance.

CodePudding user response:

Duration(minutes: (hoursDuration * 60).toInt());

CodePudding user response:

As @MuhammadQasim points out, you can do this by multiplying the original hours into minutes and rounding. This has a problem, if you care about seconds, milliseconds or microseconds, those are lost with Muhammad's solution, which is why I think it is worth posting the other end of the spectrum, where not even microseconds get rounded.

Duration parseDurationFromDouble(double hours) {
    return Duration(
      microseconds: (hours * Duration.microsecondsPerHour).toInt()
    );
}

CodePudding user response:

You can try this one. Manually converting the value into hours. minutes and seconds.

void parseDurationFromDouble(double value){
  int hours = value.toInt();
  int minutes = ((value - hours) * 60).toInt();
  int seconds = ((((value - hours) * 60) - minutes) * 60).toInt();
  print("$hours:$minutes:$seconds");
  Duration(hours: hours, minutes: minutes, seconds: seconds);
}
  • Related