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
Parameter | Optional/Required | Description |
---|---|---|
other | required | The Duration object to compare to. |
Return Type
Duration.compareTo() returns value of type int
.
✐ Examples
1 Comparing days and hours
In this example,
- We create two Duration objects
duration1
andduration2
with 3 days and 72 hours, respectively. - We use the
compareTo
method to compareduration1
withduration2
. - 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,
- We create two Duration objects
duration3
andduration4
with 120 seconds and 2 minutes, respectively. - We use the
compareTo
method to compareduration3
withduration4
. - 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,
- We create two Duration objects
duration5
andduration6
with 1 day and -1 day, respectively. - We use the
compareTo
method to compareduration5
withduration6
. - 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.