Temporal.PlainTime.compare()

可用性有限

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

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

静态方法 Temporal.PlainTime.compare() 返回一个数字(-1、0 或 1),表示第一个时间在第二个时间之前、与第二个时间相同或在第二个时间之后。它等同于逐个比较小时、分钟、秒、毫秒、微秒和纳秒字段。

语法

js
Temporal.PlainTime.compare(time1, time2)

参数

time1

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

time2

要比较的第二个时间,使用与 time1 相同的算法转换为 Temporal.PlainTime 对象。

返回值

如果 time1time2 之前,则返回 -1;如果它们相同,则返回 0;如果 time1time2 之后,则返回 1

示例

使用 Temporal.PlainTime.compare()

js
const time1 = Temporal.PlainTime.from("12:34:56");
const time2 = Temporal.PlainTime.from("12:34:57");
console.log(Temporal.PlainTime.compare(time1, time2)); // -1

const time3 = Temporal.PlainTime.from("11:34:56");
console.log(Temporal.PlainTime.compare(time1, time3)); // 1

对时间数组进行排序

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

js
const times = ["12:34:56", "11:34:56", "12:34:57"];

times.sort(Temporal.PlainTime.compare);
console.log(times);
// [ "11:34:56", "12:34:56", "12:34:57" ]

规范

规范
Temporal
# sec-temporal.plaintime.compare

浏览器兼容性

另见