Temporal.PlainYearMonth.compare()

可用性有限

此特性不是基线特性,因为它在一些最广泛使用的浏览器中不起作用。

实验性: 这是一项实验性技术
在生产中使用此技术之前,请仔细检查浏览器兼容性表格

Temporal.PlainYearMonth.compare() 静态方法返回一个数字(-1、0 或 1),指示第一个年月早于、等于还是晚于第二个年月。这等同于比较它们底层的 ISO 8601 日期。来自不同日历的两个年月,如果它们在同一个 ISO 日期开始,可能会被视为相等。

注意: PlainYearMonth 对象会跟踪一个参考 ISO 日期,该日期也用于比较。使用 Temporal.PlainYearMonth.from() 方法时会自动设置此日期,但可以使用 Temporal.PlainYearMonth() 构造函数手动设置,这会导致两个等效的年月被视为不同,如果它们具有不同的参考日期。因此,您应该避免直接使用构造函数,而是优先使用 from() 方法。

语法

js
Temporal.PlainYearMonth.compare(yearMonth1, yearMonth2)

参数

yearMonth1

一个字符串、对象或 Temporal.PlainYearMonth 实例,表示要比较的第一个年月。它使用与 Temporal.PlainYearMonth.from() 相同的算法转换为 Temporal.PlainYearMonth 对象。

yearMonth2

要比较的第二个年月,使用与 yearMonth1 相同的算法转换为 Temporal.PlainYearMonth 对象。

返回值

如果 yearMonth1 早于 yearMonth2,则返回 -1;如果它们相同,则返回 0;如果 yearMonth1 晚于 yearMonth2,则返回 1。它们通过其底层的日期值(通常是该月份的第一天)进行比较,忽略它们的日历。

示例

使用 Temporal.PlainYearMonth.compare()

js
const ym1 = Temporal.PlainYearMonth.from("2021-08");
const ym2 = Temporal.PlainYearMonth.from("2021-09");
console.log(Temporal.PlainYearMonth.compare(ym1, ym2)); // -1

const ym3 = Temporal.PlainYearMonth.from("2021-07");
console.log(Temporal.PlainYearMonth.compare(ym1, ym3)); // 1

比较不同日历中的年月

js
const ym1 = Temporal.PlainYearMonth.from({ year: 2021, month: 8 });
const ym2 = Temporal.PlainYearMonth.from({
  year: 2021,
  month: 8,
  calendar: "islamic-umalqura",
});
const ym3 = Temporal.PlainYearMonth.from({
  year: 2021,
  month: 8,
  calendar: "hebrew",
});
console.log(ym1.toString()); // "2021-08"
console.log(ym2.toString()); // "2582-12-17[u-ca=islamic-umalqura]"
console.log(ym3.toString()); // "-001739-04-06[u-ca=hebrew]"
console.log(Temporal.PlainYearMonth.compare(ym1, ym2)); // -1
console.log(Temporal.PlainYearMonth.compare(ym1, ym3)); // 1

对年月数组进行排序

compare() 函数的目的是作为比较器,传递给 Array.prototype.sort() 和相关函数。

js
const months = [
  Temporal.PlainYearMonth.from({ year: 2021, month: 8 }),
  Temporal.PlainYearMonth.from({
    year: 2021,
    month: 8,
    calendar: "islamic-umalqura",
  }),
  Temporal.PlainYearMonth.from({ year: 2021, month: 8, calendar: "hebrew" }),
];

months.sort(Temporal.PlainYearMonth.compare);
console.log(months.map((d) => d.toString()));
// [ "-001739-04-06[u-ca=hebrew]", "2021-08", "2582-12-17[u-ca=islamic-umalqura]" ]

规范

规范
Temporal
# sec-temporal.plainyearmonth.compare

浏览器兼容性

另见