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

瀏覽器相容性

另見