Temporal.PlainDateTime.prototype.toZonedDateTime()
Temporal.PlainDateTime 例項的 toZonedDateTime() 方法返回一個新的 Temporal.ZonedDateTime 例項,該例項表示與此純日期時間相同的日期時間,但位於指定的時區。
語法
js
toZonedDateTime(timeZone)
toZonedDateTime(timeZone, options)
引數
timeZone-
一個字串或一個
Temporal.ZonedDateTime例項,表示要使用的時區。如果是Temporal.ZonedDateTime例項,則使用其時區。如果是一個字串,它可以是命名時區識別符號、偏移時區識別符號,或者包含時區識別符號或偏移的日期時間字串(有關更多資訊,請參閱時區和偏移)。 options可選-
包含以下屬性的物件
disambiguation可選-
一個字串,指定當此純時間在一個時區中對應於零個或多個瞬時(通常是由於夏令時切換)時應執行的操作。可能的值有
"compatible"、"earlier"、"later"和"reject"。預設為"compatible"。有關這些值的更多資訊,請參閱從本地時間到 UTC 時間的歧義和間隙。
返回值
一個新的 Temporal.ZonedDateTime 例項,表示與此純日期時間相同的日期時間,但位於指定的時區。
異常
RangeError-
在以下情況之一中丟擲
- 任何選項無效。
timeZone不是有效的時區識別符號。- 掛鐘時間在時區中存在歧義,並且
options.disambiguation設定為"reject"。
TypeError-
如果任何引數的型別與預期不符,則丟擲此錯誤。
示例
使用 toZonedDateTime()
js
const dt = Temporal.PlainDateTime.from("2021-08-01T12:34:56");
const zdt = dt.toZonedDateTime("America/New_York");
console.log(zdt.toString()); // '2021-08-01T12:34:56-04:00[America/New_York]'
const dt2 = Temporal.PlainDateTime.from("2021-01-01T12:34:56");
const zdt2 = dt2.toZonedDateTime("America/New_York");
console.log(zdt2.toString()); // '2021-01-01T12:34:56-05:00[America/New_York]'
處理歧義時間
下面,我們有兩個掛鐘時間,我們希望在 America/New_York 時區中解釋它們。第一個,dtNotExist,由於夏令時向前切換而從未存在,所以我們需要從時間 01:05:00-05:00 或 03:05:00-04:00 中選擇。第二個,dtAmbiguous,由於夏令時向後切換而出現了兩次,所以我們需要從時間 01:05:00-04:00 或 01:05:00-05:00 中選擇。有關這種情況的更詳細解釋,請參閱從本地時間到 UTC 時間的歧義和間隙。
js
const dtNotExist = Temporal.PlainDateTime.from("2024-03-10T02:05:00");
const dtAmbiguous = Temporal.PlainDateTime.from("2024-11-03T01:05:00");
// Default: compatible
console.log(dtNotExist.toZonedDateTime("America/New_York").toString());
// '2024-03-10T03:05:00-04:00[America/New_York]'
console.log(dtAmbiguous.toZonedDateTime("America/New_York").toString());
// '2024-11-03T01:05:00-04:00[America/New_York]'
// Use the earlier time for ambiguous times
console.log(
dtNotExist
.toZonedDateTime("America/New_York", { disambiguation: "earlier" })
.toString(),
);
// '2024-03-10T01:05:00-05:00[America/New_York]'
console.log(
dtAmbiguous
.toZonedDateTime("America/New_York", { disambiguation: "earlier" })
.toString(),
);
// '2024-11-03T01:05:00-04:00[America/New_York]'
// Use the later time for ambiguous times
console.log(
dtNotExist
.toZonedDateTime("America/New_York", { disambiguation: "later" })
.toString(),
);
// '2024-03-10T03:05:00-04:00[America/New_York]'
console.log(
dtAmbiguous
.toZonedDateTime("America/New_York", { disambiguation: "later" })
.toString(),
);
// '2024-11-03T01:05:00-05:00[America/New_York]'
// Throw an error for ambiguous times
dtNotExist.toZonedDateTime("America/New_York", { disambiguation: "reject" });
// RangeError: instant is ambiguous
規範
| 規範 |
|---|
| Temporal # sec-temporal.plaindatetime.prototype.tozoneddatetime |
瀏覽器相容性
載入中…