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

Temporal.Instant.compare()

· 52CE 我爱测

The **`Temporal.Instant.compare()`** static method returns a number (-1, 0, or 1) indicating whether the first instant comes before, is the same as, or comes after the second instant. It is equivalent to comparing the Temporal/Instant/epochNanoseconds of the two instants.

The Temporal.Instant.compare() static method returns a number (-1, 0, or 1) indicating whether the first instant comes before, is the same as, or comes after the second instant. It is equivalent to comparing the Temporal/Instant/epochNanoseconds of the two instants.

Syntax

Temporal.Instant.compare(instant1, instant2)

Parameters

  • instant1
    • : A string or a Temporal.Instant instance representing the first instant to compare. It is converted to a Temporal.Instant object using the same algorithm as Temporal/Instant/from.
  • instant2
    • : The second instant to compare, converted to a Temporal.Instant object using the same algorithm as instant1.

Return value

Returns -1 if instant1 comes before instant2, 0 if they are the same, and 1 if instant1 comes after instant2.

Examples

Using Temporal.Instant.compare()

const instant1 = Temporal.Instant.from("2021-08-01T12:34:56Z");
const instant2 = Temporal.Instant.from("2021-08-01T12:34:56Z");

console.log(Temporal.Instant.compare(instant1, instant2)); // 0

const instant3 = Temporal.Instant.from("2021-08-01T13:34:56Z");
console.log(Temporal.Instant.compare(instant1, instant3)); // -1

Sorting an array of instants

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

const instants = [
  Temporal.Instant.from("2021-08-01T12:34:56Z"),
  Temporal.Instant.from("2021-08-01T12:34:56+01:00"),
  Temporal.Instant.from("2021-08-01T12:34:56-01:00"),
];

instants.sort(Temporal.Instant.compare);
console.log(instants.map((instant) => instant.toString()));
// [ '2021-08-01T11:34:56Z', '2021-08-01T12:34:56Z', '2021-08-01T13:34:56Z' ]

Specifications

Browser compatibility

See also

  • Temporal.Instant
  • Temporal/Instant/equals

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

资料来源与适用范围

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

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

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