Temporal.ZonedDateTime.prototype.toString()
Temporal.ZonedDateTime 实例的 toString() 方法返回一个字符串,该字符串以 RFC 9557 格式表示此日期-时间。
语法
toString()
toString(options)
参数
options可选-
包含以下属性的对象
calendarName可选-
是否在返回值中显示日历注释 (
[u-ca=calendar_id])。可能的值是:"auto"(默认值)-
如果日历不是
"iso8601",则包含日历注释。 "always"-
始终包含日历注释。
"never"-
从不包含日历注释。这使得返回的字符串无法恢复为相同的
Temporal.ZonedDateTime实例,尽管日期值仍然相同。 "critical"-
始终包含日历注释,并添加一个关键标志:
[!u-ca=calendar_id]。当将字符串发送到某些系统时很有用,但对 Temporal 本身没有用。
fractionalSecondDigits可选-
一个 0 到 9 之间的整数,或字符串
"auto"。默认值为"auto"。如果为"auto",则从小数秒中删除尾随零。否则,秒组件的小数部分包含这么多位数,必要时用零填充或四舍五入。 roundingMode可选-
一个字符串,指定如何对超出
fractionalSecondDigits的小数秒位数进行四舍五入。请参阅Intl.NumberFormat()。默认为"trunc"。 smallestUnit可选-
一个字符串,指定输出中包含的最小单位。可能的值是
"minute"、"second"、"millisecond"、"microsecond"和"nanosecond",或它们的复数形式,它们(除了"minute")分别等同于fractionalSecondDigits值为0、3、6、9。如果指定,则忽略fractionalSecondDigits。 timeZoneName可选-
是否在返回值中显示时区名称 (
[time_zone_id])。可能的值是:"auto"(默认值)-
始终包含时区名称。
"never"-
从不包含时区名称。这使得返回的字符串无法恢复为相同的
Temporal.ZonedDateTime实例。 "critical"-
始终包含时区名称,并添加一个关键标志:
[!time)zone_id]。当将字符串发送到某些系统时很有用,但对 Temporal 本身没有用。
offset可选-
是否在返回值中显示偏移量 (
±HH:mm)。可能的值是:"auto"(默认值)-
始终包含偏移量。
"never"-
从不包含偏移量。如果包含时区但时间不明确,或者时区也未包含,则这使得返回的字符串无法恢复为相同的
Temporal.ZonedDateTime实例。
返回值
一个以 RFC 9557 格式表示此日期-时间的字符串。偏移量和日历/时区注释按照指定包含。
异常
RangeError-
如果任何选项无效,则抛出。
TypeError-
如果
options不是对象或undefined,则抛出错误。
示例
使用 toString()
const zdt = Temporal.ZonedDateTime.from(
"2021-08-01T12:34:56[America/New_York]",
);
console.log(zdt.toString()); // '2021-08-01T12:34:56-04:00[America/New_York]'
即使对于 UTC 时区,偏移量也是 +00:00,而不是 Z。
const zdt = Temporal.ZonedDateTime.from("2021-08-01T12:34:56[UTC]");
console.log(zdt.toString()); // '2021-08-01T12:34:56+00:00[UTC]'
使用选项
有关舍入时间的示例,请参阅 Temporal.PlainTime.prototype.toString()。有关显示日历的示例,请参阅 Temporal.PlainDate.prototype.toString()。此处我们展示了如何控制时区和偏移量的显示。
const zdt = Temporal.ZonedDateTime.from(
"2021-08-01T12:34:56[America/New_York]",
);
console.log(zdt.toString({ timeZoneName: "auto", offset: "never" })); // '2021-08-01T12:34:56[America/New_York]'
console.log(zdt.toString({ timeZoneName: "never", offset: "auto" })); // '2021-08-01T12:34:56-04:00'
console.log(zdt.toString({ timeZoneName: "never", offset: "never" })); // '2021-08-01T12:34:56'
console.log(zdt.toString({ timeZoneName: "critical", offset: "never" })); // '2021-08-01T12:34:56[!America/New_York]'
规范
| 规范 |
|---|
| Temporal # sec-temporal.zoneddatetime.prototype.tostring |
浏览器兼容性
加载中…