Dart DateTime compareTo()
Syntax & Examples
Syntax of DateTime.compareTo()
The syntax of DateTime.compareTo() method is:
int compareTo(DateTime other) This compareTo() method of DateTime compares this DateTime object to other, returning zero if the values are equal.
Parameters
| Parameter | Optional/Required | Description |
|---|---|---|
other | required | the DateTime object to compare to |
Return Type
DateTime.compareTo() returns value of type int.
✐ Examples
1 Compare two DateTime objects where the first is earlier
In this example,
- We create two DateTime objects,
dt1anddt2, representing different dates. - We then use the
compareTo()method ondt1withdt2as the argument. - The method returns a negative value since
dt1is earlier thandt2. - We print the result to standard output.
Dart Program
void main() {
var dt1 = DateTime(2024, 5, 3);
var dt2 = DateTime(2024, 5, 4);
var result = dt1.compareTo(dt2);
print(result);
}Output
-1
2 Compare two DateTime objects where both are equal
In this example,
- We create two identical DateTime objects,
dt1anddt2, representing the same date. - We then use the
compareTo()method ondt1withdt2as the argument. - The method returns zero since both DateTime objects are equal.
- We print the result to standard output.
Dart Program
void main() {
var dt1 = DateTime(2024, 5, 3);
var dt2 = DateTime(2024, 5, 3);
var result = dt1.compareTo(dt2);
print(result);
}Output
0
3 Compare two DateTime objects where the first is later
In this example,
- We create two DateTime objects,
dt1anddt2, representing different dates. - We then use the
compareTo()method ondt1withdt2as the argument. - The method returns a positive value since
dt1is later thandt2. - We print the result to standard output.
Dart Program
void main() {
var dt1 = DateTime(2024, 5, 4);
var dt2 = DateTime(2024, 5, 3);
var result = dt1.compareTo(dt2);
print(result);
}Output
1
Summary
In this Dart tutorial, we learned about compareTo() method of DateTime: the syntax and few working examples with output and detailed explanation for each example.