Skip to content
jshacks.dev
Fundamentals

Compare two Temporal dates

Compare two Temporal dates with compare and equals, and see why strict equality is false and the less-than operator throws a TypeError. Node.js 26.

2 min read
Summarize in AI

new Date(a) < new Date(b) works because dates turn into numbers, which is also why date1 === date2 is false. Temporal objects do not convert to numbers at all, and they give you compare() instead, in Node.js 26.

JavaScript
const a = Temporal.PlainDate.from('2026-11-13');
const b = Temporal.PlainDate.from('2026-11-14');

console.log(Temporal.PlainDate.compare(a, b));
console.log(a.equals('2026-11-13'));
console.log(a === Temporal.PlainDate.from('2026-11-13'));
console.log([b, a].toSorted(Temporal.PlainDate.compare).map(String));

try {
  console.log(a < b);
} catch (error) {
  console.log(error.name + ': ' + error.message);
}
Text
-1
true
false
[ '2026-11-13', '2026-11-14' ]
TypeError: Do not use Temporal.PlainDate.prototype.valueOf; use Temporal.PlainDate.prototype.compare for comparison.

Temporal.PlainDate.compare(a, b) returns -1, 0 or 1, which is the contract Array.prototype.sort expects, so toSorted(Temporal.PlainDate.compare) works as it stands. equals() compares the date and the calendar and takes a string, as the second line shows. The third line is the trap: two separate objects for the same date are not ===. And a < b throws TypeError: Do not use Temporal.PlainDate.prototype.valueOf; use Temporal.PlainDate.prototype.compare for comparison., which is deliberate: the operator is blocked so that an accidental comparison fails loudly. See the Temporal documentation for PlainDate.

The same pair of methods exists on every Temporal type, with the same names. A Map or Set keyed by PlainDate objects will not find a second instance of the same date, so key by toString().

Taggednode 26
Share

More snippets

Fundamentals

Sort dates in an array

Sort an array of Date objects by subtracting them, and see why the default sort orders dates by weekday name. Works in every Node.js release.

1 min read
Fundamentals

Sort by multiple keys

Sort records by several keys in one comparator with toSorted, falling through to the next key when the first ties. Needs Node.js 20, stable since ES2019.

1 min read
Fundamentals

Get a random item from an array

Pick a random item from an array with Math.random, and see why rounding the index instead of flooring it makes the middle item twice as likely. Node.js 18.

2 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.