Temporal.Instant.prototype.toString()

可用性有限

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

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

toString() 方法是 Temporal.Instant 实例的一个方法,它返回一个字符串,该字符串使用指定的时区以 RFC 9557 格式表示此即时值。

语法

js
toString()
toString(options)

参数

options 可选

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

fractionalSecondDigits 可选

一个 0 到 9 之间的整数,或字符串 "auto"。默认值为 "auto"。如果为 "auto",则从小数秒中删除尾随零。否则,秒组件的小数部分包含这么多位数,必要时用零填充或四舍五入。

roundingMode 可选

一个字符串,指定如何对超出 fractionalSecondDigits 的小数秒位数进行四舍五入。请参阅 Intl.NumberFormat()。默认为 "trunc"

smallestUnit 可选

一个字符串,指定输出中包含的最小单位。可能的值是 "minute""second""millisecond""microsecond""nanosecond",或它们的复数形式,它们(除了 "minute")分别等同于 fractionalSecondDigits 值为 0369。如果指定,则忽略 fractionalSecondDigits

timeZone 可选

可以是字符串或 Temporal.ZonedDateTime 实例,表示要使用的时区。如果为 Temporal.ZonedDateTime 实例,则使用其时区。如果为字符串,则可以是命名时区标识符、偏移时区标识符,或者包含时区标识符或偏移量的日期时间字符串(有关更多信息,请参阅 时区和偏移量)。默认为 "UTC"

返回值

一个使用指定时区的 RFC 9557 格式字符串,表示此即时值。不包含任何注解,例如时区名称。

异常

RangeError

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

示例

使用 toString()

js
const instant = Temporal.Instant.fromEpochMilliseconds(1627814412345);
console.log(instant.toString()); // '2021-08-01T10:40:12.345Z'

// Stringification implicitly calls toString()
console.log(`${instant}`); // '2021-08-01T10:40:12.345Z'

使用选项

js
const instant = Temporal.Instant.fromEpochMilliseconds(1627814412345);
console.log(instant.toString({ fractionalSecondDigits: 1 })); // '2021-08-01T10:40:12.3Z'
console.log(instant.toString({ smallestUnit: "minute" })); // '2021-08-01T10:40Z'
console.log(instant.toString({ timeZone: "America/New_York" })); // '2021-08-01T06:40:12.345-04:00'

// The time zone name automatically resolves to the correct offset
// based on the instant; for example, America/New_York is UTC-4 in summer,
// but UTC-5 in winter.
const instant2 = Temporal.Instant.fromEpochMilliseconds(1577836800000);
console.log(instant2.toString({ timeZone: "UTC" })); // '2029-12-31T23:00:00Z'
console.log(instant2.toString({ timeZone: "America/New_York" })); // '2019-12-31T19:00:00-05:00'

规范

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

浏览器兼容性

另见