JS Temporal Compare
Date Comparison
In JavaScript, objects cannot be compared using operators like <, >, ==, or ===.
Always use the equals() or compare() methods rather than standard equality operators.
Temporal compare() and equals()
All temporal objects have their own compare() methods:
- Temporal.Instant.compare(instant1, instant2)
- Temporal.PlainDate.compare(plaindate1, plaindate2)
- Temporal.PlainTime.compare(plaintime1, plaintime2)
- Temporal.PlainYearMonth.compare(plainyearmonth1, plainyearmonth2)
- Temporal.PlainMonthDay.compare(plainmonthday1 plainmonthday2)
- Temporal.PlainDateTime.compare(plaindatetime1,plaindatetime2)
- Temporal.ZonedDateTime.compare(zoneddtatime1, zoneddtatime2)
- Temporal.Duration.compare(duration1, duration2)
Most temporal objects have their own equals() methods:
- instant.equals(instant)
- plaindate.equals(plaindate)
- plaintime.equals(plaintime)
- plainyearmonth.equals(plainyearmonth)
- plainmonthday.equals(plainmonthday)
- plaindateTime.equals(plaindatetime)
- zoneddateTime.equals(zoneddtatime)
The Temporal.Duration object does not have an equals() method due to the
complexity of handling different representations of the same duration.
Temporal.Duration.compare() method.
Temporal.PlainDate.compare()
The compare() method returns:
- -1 if the first date is earlier
- 1 if it is later
- 0 if they are equal
Example
// Create two Temporal objects
const date1 = Temporal.PlainDate.from("2026-05-17");
const date2 = Temporal.PlainDate.from("2024-12-25");
// Compare the dates
result = Temporal.PlainDate.compare(date1, date2);
Try it Yourself »
The compare() method is designed to be passed directly into the JavaScript Array.sort() method:
Example
// Create an Array of dates
const dates = [
Temporal.PlainDate.from("2026-05-17"),
Temporal.PlainDate.from("2022-01-01"),
Temporal.PlainDate.from("2024-12-25")
];
// Sort chronologically
dates.sort(Temporal.PlainDate.compare);
Try it Yourself »
Temporal.Duration.Compare()
Examples
// Create two Durations
const d1 = Temporal.Duration.from({ hours:1, minutes:30 });
const d2 = Temporal.Duration.from({ minutes:90 });
// Compare the Durations
let result = Temporal.Duration.compare(d1, d2);
Try it Yourself »
// Create two Durations
const d1 = Temporal.Duration.from({ hours:1, minutes:30 });
const d2 = Temporal.Duration.from({ hours:1, minutes:30 });
// Compare the Durations
let result = Temporal.Duration.compare(d1, d2);
Try it Yourself »
Note that the two examples above both return 0.
The PlainDate equals() Method
The equals() method returns
true if both dates are equal.
Example
// Create two Temporal objects
const date1 = Temporal.PlainDate.from('2026-05-17');
const date2 = Temporal.PlainDate.from('2026-05-17');
let result = date1.equals(date2);
Try it Yourself »