大网数据广告活动
Web 标准与前端开发

Temporal.PlainTime.compare()

· 52CE 我爱测

The **`Temporal.PlainTime.compare()`** static method returns a number (-1, 0, or 1) indicating whether the first time comes before, is the same as, or comes after the second time. It is equivalent to comparing the hour, minute, second, millisecond, microsecond, and nanosecond fie

The Temporal.PlainTime.compare() static method returns a number (-1, 0, or 1) indicating whether the first time comes before, is the same as, or comes after the second time. It is equivalent to comparing the hour, minute, second, millisecond, microsecond, and nanosecond fields one by one.

Syntax

Temporal.PlainTime.compare(time1, time2)

Parameters

  • time1
    • : A string, an object, or a Temporal.PlainTime instance representing the first time to compare. It is converted to a Temporal.PlainTime object using the same algorithm as Temporal/PlainTime/from.
  • time2
    • : The second time to compare, converted to a Temporal.PlainTime object using the same algorithm as time1.

Return value

Returns -1 if time1 comes before time2, 0 if they are the same, and 1 if time1 comes after time2.

Examples

Using Temporal.PlainTime.compare()

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

Sorting an array of times

The purpose of this compare() function is to act as a comparator to be passed to Array.prototype.sort() and related functions.

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" ]

Specifications

Browser compatibility

See also

  • Temporal.PlainTime
  • Temporal/PlainTime/equals

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。