Comparisons

Comparisons

All datetime and time interval types support equality comparisons with ==, and all but Period support the inequality operators (<, >, <=, etc.) as well. They also implement Comparable for easy sorting. How the comparisons work varies by type, however.

Local types

Local dates and time comparisons are straightforward. If one LocalDateTime is earlier than another, then dt1 < dt2.

Some examples:

final dt1 = LocalDateTime(2023, 5, 6, 12, 0);
final dt2 = LocalDateTime(2023, 5, 6, 13, 0);
dt1 != dt2;
dt1 < dt2;
dt2 > dt1;
dt1.compareTo(dt2) == -1;

Absolute types

Absolute datetimes work differently, though. Inequality comparisons and compareTo use the underlying Instant and ignore everything else. For example, Jan 1, 2000 12:00 PM EST > Jan 1, 2000 1:00 PM PST because EST is 3 hours ahead of PST.

final est = ZonedDateTime.withZoneId('America/New_York', 2000, 1, 1, 12);
final pst = ZonedDateTime.withZoneId('America/Los_Angeles', 2000, 1, 1, 1);
est > pst == true;

Equality comparisons, however, are a special case. They really do compare everything. Two ZonedDateTimes are only equal if all fields—including the time zone—match. If you just want to test that they represent the same moment in time use the compareTo method, or compare the underlying Instant:

final date1 = ZonedDateTime.withZoneId('America/New_York', 2000, 1, 1, 12);
final date2 = ZonedDateTime.withZoneId('America/Los_Angeles', 2000, 1, 1, 9);
date1 != date2;
date1.compareTo(date2) == 0;
date1.toInstant() == date2.toInstant();
I’m unhappy with the way equality comparisons work for absolute types. Having == use different criteria than < or <= is confusing. I see two possibilities: live with it, or replace the inequality operators with named methods. If you’ve got an opinion, I’d love to hear it.

Relative types

Timespan comparisons work exactly like you would expect. For example:

Timespan(hours: 48) == Timespan(days: 2);
Timespan(seconds: 10) < Timespan(hours: 1);
Timespan(seconds: 10) >= Timespan(seconds: 10);

Period comparisons, on the other hand, are much more limited. You can only compare them for equality:

Period(years: 1, months: 2) == Period(years: 1, months: 2);
Period(years: 1, months: 2) != Period(years: 2, months: 1);
The nerdy details: Period doesn’t support inequality comparisons because it’s not well-ordered. While you can definitively say that a period of 1 month is less than 2 months, you can’t definitively say that 1 month and 30 days is less than 2 months. It depends on the actual months.