compareTo method Null safety

int compareTo(
  1. DateTime other
)

Compares this DateTime object to other, returning zero if the values are equal.

Returns -1 if this is null

A compareTo function returns:

  • a negative value if this DateTime isBefore other.
  • 0 if this DateTime isAtSameMomentAs other, and
  • a positive value otherwise (when this DateTime isAfter other).
final now = DateTime.now();
final future = now.add(const Duration(days: 2));
final past = now.subtract(const Duration(days: 2));
final newDate = now.toUtc();

print(now.compareTo(future)); // -1
print(now.compareTo(past)); // 1
print(now.compareTo(newDate)); // 0

Implementation

int compareTo(DateTime other) => _value?.compareTo(other) ?? -1;