Dart Duration compareTo()
Syntax & Examples


Duration.compareTo() method

The `compareTo` method in Dart compares this Duration to another, returning zero if the values are equal.


Syntax of Duration.compareTo()

The syntax of Duration.compareTo() method is:

 int compareTo(Duration other) 

This compareTo() method of Duration compares this Duration to other, returning zero if the values are equal.

Parameters

ParameterOptional/RequiredDescription
otherrequiredThe Duration object to compare to.

Return Type

Duration.compareTo() returns value of type int.



✐ Examples

1 Comparing days and hours

In this example,

  1. We create two Duration objects duration1 and duration2 with 3 days and 72 hours, respectively.
  2. We use the compareTo method to compare duration1 with duration2.
  3. We then print the result to standard output.

Dart Program

void main() {
  Duration duration1 = Duration(days: 3);
  Duration duration2 = Duration(hours: 72);
  int result1 = duration1.compareTo(duration2);
  print('Result1: $result1');
}

Output

Result1: 0

2 Comparing seconds and minutes

In this example,

  1. We create two Duration objects duration3 and duration4 with 120 seconds and 2 minutes, respectively.
  2. We use the compareTo method to compare duration3 with duration4.
  3. We then print the result to standard output.

Dart Program

void main() {
  Duration duration3 = Duration(seconds: 120);
  Duration duration4 = Duration(minutes: 2);
  int result2 = duration3.compareTo(duration4);
  print('Result2: $result2');
}

Output

Result2: 0

3 Comparing positive and negative durations

In this example,

  1. We create two Duration objects duration5 and duration6 with 1 day and -1 day, respectively.
  2. We use the compareTo method to compare duration5 with duration6.
  3. We then print the result to standard output.

Dart Program

void main() {
  Duration duration5 = Duration(days: 1);
  Duration duration6 = Duration(days: -1);
  int result3 = duration5.compareTo(duration6);
  print('Result3: $result3');
}

Output

Result3: 1

Summary

In this Dart tutorial, we learned about compareTo() method of Duration: the syntax and few working examples with output and detailed explanation for each example.