Temporal.ZonedDateTime.prototype.toString()

可用性有限

此特性不是基線特性,因為它在一些最廣泛使用的瀏覽器中不起作用。

實驗性: 這是一項實驗性技術
在生產中使用此技術之前,請仔細檢查瀏覽器相容性表格

Temporal.ZonedDateTime 例項的 toString() 方法返回一個字串,該字串以 RFC 9557 格式表示此日期-時間。

語法

js
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 值為 0369。如果指定,則忽略 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()

js
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

js
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()。此處我們展示瞭如何控制時區和偏移量的顯示。

js
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

瀏覽器相容性

另見