Sub topic 15
Comparing and Sorting Temporal Values
This chapter assumes you can create Temporal values with from() and constructors, know how the Plain types differ from Instant and ZonedDateTime, and have Temporal available as a global or imported from the polyfill as shown earlier.
With legacy Date, you could write a < b and get an answer, because Date converts itself to a number. Temporal does not allow that. Comparing values takes two methods: a static compare() that orders values, and an instance equals() that checks whether two values are the same. This chapter covers how each one works, where they disagree, and how to sort data with them.
Why relational operators throw
Every Temporal type defines a valueOf() method that throws a TypeError. The <, >, <=, and >= operators call valueOf(), so using them fails at once:
const a = Temporal.PlainDate.from('2024-01-15');
const b = Temporal.PlainDate.from('2024-05-01');
try {
console.log(a < b);
} catch (e) {
console.log(e instanceof TypeError); // true
}The designers chose this on purpose. A silent numeric conversion would hide questions that matter. For example, should two ZonedDateTime values in different time zones be ordered by wall-clock time or by exact time? A thrown error makes you pick a method that answers that question explicitly.
Ordering with static compare
Every type except PlainMonthDay has a static compare(one, two) method. It returns -1 if one comes first, 0 if the two are equal for ordering purposes, and 1 if one comes later. The arguments can be Temporal objects, ISO strings, or property bags, because both are converted the same way from() converts its input.
console.log(Temporal.PlainDate.compare('2024-01-15', '2024-05-01')); // -1
console.log(Temporal.PlainTime.compare('09:30', '09:30')); // 0
console.log(Temporal.Instant.compare(
'2024-03-15T12:00:00Z',
'2024-03-15T11:59:59Z'
)); // 1This contract matches the comparator that Array.prototype.sort expects, so you can pass compare directly:
const dates = ['2024-05-01', '2023-12-25', '2024-01-15'].map((s) =>
Temporal.PlainDate.from(s)
);
dates.sort(Temporal.PlainDate.compare);
console.log(dates.map(String)); // ['2023-12-25', '2024-01-15', '2024-05-01']Common sorting patterns
To sort in descending order, swap the arguments. To sort records, compare a field on each record:
const tasks = [
{ name: 'Report', due: Temporal.PlainDate.from('2024-04-10') },
{ name: 'Invoice', due: Temporal.PlainDate.from('2024-02-01') },
{ name: 'Review', due: Temporal.PlainDate.from('2024-03-05') },
];
// Latest first
tasks.sort((x, y) => Temporal.PlainDate.compare(y.due, x.due));
console.log(tasks.map((t) => t.name)); // ['Report', 'Review', 'Invoice']
// Earliest due date
const earliest = tasks.reduce((min, t) =>
Temporal.PlainDate.compare(t.due, min.due) < 0 ? t : min
);
console.log(earliest.name); // 'Invoice'
// Half-open range check: start <= d < end
function inRange(d, start, end) {
return (
Temporal.PlainDate.compare(d, start) >= 0 &&
Temporal.PlainDate.compare(d, end) < 0
);
}
console.log(inRange(tasks[1].due, '2024-03-01', '2024-04-01')); // trueEquality with equals
Each type also has an instance equals(other) method, which returns a boolean. equals() is stricter than compare(). It checks every part of the value, while compare() looks only at what determines order.
| Type | `compare()` returns 0 when | `equals()` also requires |
|---|---|---|
| `PlainDate`, `PlainDateTime`, `PlainYearMonth` | Same ISO date (and time) | Same calendar |
| `PlainTime` | Same time | Nothing extra |
| `Instant` | Same exact time | Nothing extra |
| `ZonedDateTime` | Same exact time | Same time zone and calendar |
| `PlainMonthDay` | No `compare()` method | Same month, day, and calendar |
| `Duration` | Same total length | No `equals()` method; use `compare()` |
The ZonedDateTime row causes the most surprises. Two values that describe the same moment in different zones are equal for ordering but not equal under equals():
const london = Temporal.ZonedDateTime.from('2024-03-15T12:00:00+00:00[Europe/London]');
const tokyo = london.withTimeZone('Asia/Tokyo');
console.log(Temporal.ZonedDateTime.compare(london, tokyo)); // 0
console.log(london.equals(tokyo)); // false
console.log(london.toInstant().equals(tokyo.toInstant())); // trueIf you need to know whether two events happen at the same moment, convert both to Instant first. Calendars work the same way: PlainDate.from('2024-03-15').withCalendar('hebrew') compares as 0 against the ISO date, but equals() returns false.
Comparing durations
Temporal.Duration.compare() compares total length, so PT1H30M equals PT90M. Days count as 24 hours unless relativeTo is a ZonedDateTime. Years, months, and weeks have no fixed length, so you must supply a relativeTo starting point, or the call throws a RangeError:
console.log(Temporal.Duration.compare({ hours: 1, minutes: 30 }, { minutes: 90 })); // 0
try {
Temporal.Duration.compare({ months: 1 }, { days: 30 });
} catch (e) {
console.log(e instanceof RangeError); // true
}
console.log(Temporal.Duration.compare({ months: 1 }, { days: 30 }, { relativeTo: '2024-02-01' })); // -1
console.log(Temporal.Duration.compare({ months: 1 }, { days: 30 }, { relativeTo: '2024-01-01' })); // 1The answer depends on the month: February 2024 has 29 days and January has 31.
Sorting PlainMonthDay values
PlainMonthDay has no compare() method, because a month and day without a year has no single ordering when calendars differ. For ISO birthdays or anniversaries, give each value a reference year and compare the resulting dates. Use a leap year so that 02-29 stays valid:
const birthdays = ['12-01', '02-29', '07-04'].map((s) => Temporal.PlainMonthDay.from(s));
birthdays.sort((x, y) =>
Temporal.PlainDate.compare(x.toPlainDate({ year: 2024 }), y.toPlainDate({ year: 2024 }))
);
console.log(birthdays.map(String)); // ['02-29', '07-04', '12-01']Gotchas with string and Map keys
Comparing ISO strings with < seems to work for PlainDate values in years 0000 to 9999. It fails for extended years such as +010000 or -000001. It also fails for ZonedDateTime strings, whose offsets differ between zones. Use compare() rather than string comparison.
A Map or Set matches keys by object identity, so two equal PlainDate objects count as separate keys. Use toString() as the key instead. For exact moments, key on toInstant().toString() or epochNanoseconds so that the same moment in different zones gets the same key.
Exercise
You have an array of ZonedDateTime meeting start times in several time zones. Write code that sorts them chronologically and then removes entries that start at the same exact moment as an earlier entry.
Show answer
Sort with meetings.sort(Temporal.ZonedDateTime.compare), which orders by exact time regardless of zone. Then deduplicate with a Set keyed on the exact moment: const seen = new Set(); const unique = meetings.filter((m) => { const k = m.epochNanoseconds; if (seen.has(k)) return false; seen.add(k); return true; });. Do not use equals() for deduplication, because it returns false for the same moment in different zones.
Exercise
What does Temporal.Duration.compare({ weeks: 1 }, { days: 7 }) do, and how would you fix it?
Show answer
It throws a RangeError, because weeks are a calendar unit and need a starting point. Pass a relativeTo option, for example Temporal.Duration.compare({ weeks: 1 }, { days: 7 }, { relativeTo: '2024-01-01' }), which returns 0.
Exercise
Why does Temporal.PlainDate.from('2024-03-15') == Temporal.PlainDate.from('2024-03-15') print false, and what should you write instead?
Show answer
== between two objects compares identity, and these are two different objects. Use a.equals(b), or check Temporal.PlainDate.compare(a, b) === 0 if calendars should be ignored.