Home > Back-end >  How to directly divide two Duration objects in Dart?
How to directly divide two Duration objects in Dart?

Time:04-16

In Dart, let's say you have:

Duration duration01 = Duration(milliseconds: 10000);
Duration duration02 = Duration(milliseconds: 100);

I know that while add or subtract seems to work, doing:

Duration result = duration01 / duration02;

does not work.

And I know how to do it using basic math by unwrapping and re-wrapping the duration objects... but is there a way to do it directly like I am attempting?

CodePudding user response:

Dividing one Duration by another is not something that most people need to do, so there's no built-in way to do it. Dividing one Duration by another certainly should not result in a Duration object; that doesn't make sense.

You always can convert the Duration objects to microseconds and then perform arithmetic. Since Duration does not have operator /, you can add one as an extension method to make it more convenient:

extension DurationDivision on Duration {
  double operator / (Duration other) =>
      inMicroseconds / other.inMicroseconds;
}

void main() {
  Duration duration01 = Duration(milliseconds: 10000);
  Duration duration02 = Duration(milliseconds: 100);
  print(duration01 / duration02); // Prints: 100
}

CodePudding user response:

You can simply use the functions provided by the Duration object.

try this code:

Duration duration01 = Duration(milliseconds: 10000);
  Duration duration02 = Duration(milliseconds: 100);

  Duration result = Duration(
    milliseconds: duration01.inMilliseconds ~/ duration02.inMilliseconds,
  );

You can also use methods other than Duration.inMilliseconds to get the duration object in any form you want, some of them are:

  • inDays
  • inHours
  • inMicroseconds
  • inMinutes
  • inSeconds
  • Related