Temporal.PlainTime.prototype.since()
since()
方法用于
实例,返回一个新的 Temporal.PlainTime
对象,表示从另一个可被 Temporal.Duration
转换的时间到此时间的时间差。如果另一个时间在当前时间之前,则时间差为正;如果在当前时间之后,则为负。Temporal.PlainTime.from()
此方法执行 this - other
。要执行 other - this
,请使用
方法。until()
语法
since(other)
since(other, options)
参数
其他
-
一个字符串、对象或
实例,表示要从中减去的时间。它使用与Temporal.PlainTime
相同的算法转换为Temporal.PlainTime.from()
Temporal.PlainTime
对象。 options
可选-
包含
选项的对象,包括Temporal.Duration.prototype.round()
largestUnit
、roundingIncrement
、roundingMode
和smallestUnit
。largestUnit
和smallestUnit
仅接受以下单位:“hours”、“minutes”、“seconds”、“milliseconds”、“microseconds”、“nanoseconds”或它们的单数形式。对于largestUnit
,默认值"auto"
表示"hours"
。对于smallestUnit
,默认值为"nanoseconds"
。
返回值
一个表示从 other
到此时间的时间差(since
)的新的
对象。如果 Temporal.Duration
other
在此时间之前,则时间差为正;如果在此时间之后,则为负。
异常
RangeError
-
如果任何选项无效,则抛出。
示例
使用 since()
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
的小数部分会被截断。你可以使用 roundingIncrement
和 roundingMode
选项对其进行舍入。
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 |
浏览器兼容性
加载中…