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

ParameterOptional/RequiredDescription
otherrequiredthe 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,

  1. We create two DateTime objects, dt1 and dt2, representing different dates.
  2. We then use the compareTo() method on dt1 with dt2 as the argument.
  3. The method returns a negative value since dt1 is earlier than dt2.
  4. 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,

  1. We create two identical DateTime objects, dt1 and dt2, representing the same date.
  2. We then use the compareTo() method on dt1 with dt2 as the argument.
  3. The method returns zero since both DateTime objects are equal.
  4. 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,

  1. We create two DateTime objects, dt1 and dt2, representing different dates.
  2. We then use the compareTo() method on dt1 with dt2 as the argument.
  3. The method returns a positive value since dt1 is later than dt2.
  4. 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.