Temporal.ZonedDateTime.prototype.withTimeZone()
Temporal.ZonedDateTime 例項的 withTimeZone() 方法返回一個新的 Temporal.ZonedDateTime 物件,該物件表示與此日期時間相同的時刻,但使用新的時區。由於所有 Temporal 物件都被設計為不可變,此方法本質上作為日期時間 timeZoneId 屬性的設定器。
要替換日期時間元件屬性,請使用 with() 方法。要替換其日曆,請使用 withCalendar() 方法。
語法
js
withTimeZone(timeZone)
引數
timeZone-
一個字串或一個
Temporal.ZonedDateTime例項,表示要使用的時區。如果是Temporal.ZonedDateTime例項,則使用其時區。如果是一個字串,它可以是命名時區識別符號、偏移時區識別符號,或者包含時區識別符號或偏移的日期時間字串(有關更多資訊,請參閱時區和偏移)。
返回值
一個新的 Temporal.ZonedDateTime 物件,表示與此日期時間相同的時刻,但使用新的時區。
異常
TypeError-
如果
timeZone不是字串或Temporal.ZonedDateTime例項,則丟擲此錯誤。 RangeError-
如果時區名稱無效,則丟擲此錯誤。
示例
使用 withTimeZone()
js
const meetingTime = Temporal.ZonedDateTime.from(
"2021-08-01T12:00[America/New_York]",
);
const meetingTimeInParis = meetingTime.withTimeZone("Europe/Paris");
console.log(meetingTimeInParis.toString()); // 2021-08-01T18:00:00+02:00[Europe/Paris]
在保持相同掛鐘時間的同時替換時區
在您希望保持掛鐘時間不變但更改時區(並導致不同的時刻)的罕見情況下,請先將其轉換為 Temporal.PlainDateTime
js
const meetingTime = Temporal.ZonedDateTime.from(
"2021-08-01T12:00[America/New_York]",
);
const meetingTimeInParis = meetingTime
.toPlainDateTime()
.toZonedDateTime("Europe/Paris");
console.log(meetingTimeInParis.toString()); // 2021-08-01T12:00:00+02:00[Europe/Paris]
規範
| 規範 |
|---|
| Temporal # sec-temporal.zoneddatetime.prototype.withtimezone |
瀏覽器相容性
載入中…