Temporal.Instant.prototype.round()

可用性有限

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

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

round() 方法是 Temporal.Instant 实例的一个方法,它返回一个新的 Temporal.Instant 对象,该对象表示将此时间戳舍入到指定单位后的结果。

语法

js
round(smallestUnit)
round(options)

参数

smallestUnit(最小单位)

表示 smallestUnit 选项的字符串。这是一个便捷的重载,因此 round(smallestUnit) 等价于 round({ smallestUnit }),其中 smallestUnit 是一个字符串。

options

一个包含以下部分或全部属性的对象(按检索和验证的顺序):

roundingIncrement 可选

一个(截断为整数的)数字,表示给定 smallestUnit 的舍入增量。默认为 1。增量和 smallestUnit 必须能整除 24 小时;例如,45 秒是 86400 秒的除数,100 分钟是 3600 分钟的除数。这比其他类的 round() 方法的要求略微宽松,其他类要求增量是该单位最大值的除数。

roundingMode 可选

一个字符串,指定如何对 smallestUnit 的小数部分进行四舍五入。参见 Intl.NumberFormat()。默认为 "halfExpand"

smallestUnit(最小单位)

一个字符串,表示输出中包含的最小单位。该值必须是以下之一:"hour""minute""second""millisecond""microsecond""nanosecond",或它们的复数形式。对于大于 "nanosecond" 的单位,smallestUnit 的小数部分将根据 roundingIncrementroundingMode 设置进行舍入。

返回值

一个 Temporal.Instant 新对象,表示将此时间戳舍入到指定单位后的结果,其中所有小于 smallestUnit 的单位都将被归零。

异常

RangeError

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

示例

小单位的四舍五入

js
const instant = Temporal.Instant.fromEpochMilliseconds(1000);
const roundedInstant = instant.round("second");
console.log(roundedInstant.epochMilliseconds); // 1000

const instant2 = instant.round("minute");
console.log(instant2.epochMilliseconds); // 0

规范

规范
Temporal
# sec-temporal.instant.prototype.round

浏览器兼容性

另见