The purpose of this compare()
function is to act as a comparator to be passed to Array.prototype.sort()
and related functions.
const dateTimes = [
Temporal.ZonedDateTime.from("2021-08-01T00:00:00[America/New_York]"),
Temporal.ZonedDateTime.from("2021-08-01T00:00:00[Asia/Hong_Kong]"),
Temporal.ZonedDateTime.from("2021-08-01T00:00:00[Europe/London]"),
];
dateTimes.sort(Temporal.ZonedDateTime.compare);
console.log(dateTimes.map((d) => d.toString()));
// [ "2021-08-01T00:00:00+08:00[Asia/Hong_Kong]", "2021-08-01T00:00:00+01:00[Europe/London]", "2021-08-01T00:00:00-04:00[America/New_York]" ]
Note that they are compared by their instant values. In the very rare case where you want to compare them by their wall-clock times, convert them to PlainDateTime
first.
const dateTimes = [
Temporal.ZonedDateTime.from("2021-08-01T00:00:00[America/New_York]"),
Temporal.ZonedDateTime.from("2021-08-01T00:00:00[Asia/Hong_Kong]"),
Temporal.ZonedDateTime.from("2021-08-01T00:00:00[Europe/London]"),
];
dateTimes.sort((a, b) =>
Temporal.PlainDateTime.compare(a.toPlainDateTime(), b.toPlainDateTime()),
);
console.log(dateTimes.map((d) => d.toString()));
// [ "2021-08-01T00:00:00-04:00[America/New_York]", "2021-08-01T00:00:00+08:00[Asia/Hong_Kong]", "2021-08-01T00:00:00+01:00[Europe/London]" ]