Temporal.PlainTime.prototype.since()

可用性有限

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

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

since() 方法用于 Temporal.PlainTime 实例,返回一个新的 Temporal.Duration 对象,表示从另一个可被 Temporal.PlainTime.from() 转换的时间到此时间的时间差。如果另一个时间在当前时间之前,则时间差为正;如果在当前时间之后,则为负。

此方法执行 this - other。要执行 other - this,请使用 until() 方法。

语法

js
since(other)
since(other, options)

参数

其他

一个字符串、对象或 Temporal.PlainTime 实例,表示要从中减去的时间。它使用与 Temporal.PlainTime.from() 相同的算法转换为 Temporal.PlainTime 对象。

options 可选

包含 Temporal.Duration.prototype.round() 选项的对象,包括 largestUnitroundingIncrementroundingModesmallestUnitlargestUnitsmallestUnit 仅接受以下单位:“hours”、“minutes”、“seconds”、“milliseconds”、“microseconds”、“nanoseconds”或它们的单数形式。对于 largestUnit,默认值 "auto" 表示 "hours"。对于 smallestUnit,默认值为 "nanoseconds"

返回值

一个表示从 other 到此时间的时间差(since)的新的 Temporal.Duration 对象。如果 other 在此时间之前,则时间差为正;如果在此时间之后,则为负。

异常

RangeError

如果任何选项无效,则抛出。

示例

使用 since()

js
const lunchTime = Temporal.PlainTime.from("12:30:00");
const now = Temporal.Now.plainTimeISO();
const duration = now.since(lunchTime);
console.log(`You had lunch ${duration.toLocaleString("en-US")} ago`);
// Example output: "You had lunch 3 hr, 42 min, 21 sec, 343 ms, 131 μs, 718 ns ago"

const duration2 = now.since(lunchTime, { smallestUnit: "minutes" });
console.log(`You had lunch ${duration2.toLocaleString("en-US")} ago`);
// Example output: "You had lunch 3 hr, 42 min ago"

const duration3 = now.since(lunchTime, {
  largestUnit: "minutes",
  smallestUnit: "minutes",
});
console.log(`You had lunch ${duration3.toLocaleString("en-US")} ago`);
// Example output: "You had lunch 222 min ago"

舍入结果

默认情况下,smallestUnit 的小数部分会被截断。你可以使用 roundingIncrementroundingMode 选项对其进行舍入。

js
const time1 = Temporal.PlainTime.from("12:30:00");
const time2 = Temporal.PlainTime.from("12:30:01");
const duration = time2.since(time1, {
  smallestUnit: "seconds",
  roundingIncrement: 15,
  roundingMode: "ceil",
});
console.log(duration.toString()); // "PT15S"

规范

规范
Temporal
# sec-temporal.plaintime.prototype.since

浏览器兼容性

另见