首頁  >  問答  >  主體

如何使用Intl.dateTimeFormat在四個時區中以標準時間顯示時間戳記的值?

我希望能夠在使用者給定的時區中顯示時間戳記。我注意到,即使使用像 date-fns-tz 這樣的專用庫,它似乎也會傳回沒有意義的值。

在幕後他們顯然使用 Intl,當我使用該模組時,它似乎沒有提供正確的值。

const zones = ['PST', 'MST', 'CST', 'EST'];
zones.forEach((timeZone) =>
  console.log(
    new Intl.DateTimeFormat('en-US', {
      timeZone,
      timeStyle: 'full',
      dateStyle: 'full',
    }).format(1588743894000)
  )
);

輸出:

Tuesday, May 5, 2020 at 10:44:54 PM Pacific Daylight Time
Tuesday, May 5, 2020 at 10:44:54 PM GMT-07:00
Wednesday, May 6, 2020 at 12:44:54 AM Central Daylight Time
Wednesday, May 6, 2020 at 12:44:54 AM GMT-05:00

但這不應該是四個不同的值嗎?

P粉724737511P粉724737511182 天前345

全部回覆(1)我來回復

  • P粉232793765

    P粉2327937652024-04-01 00:42:27

    您正在指定三字母時區縮寫,它期望的是 IANA 時區 (https://tc39.es/ecma402/#sec-time-zone-names)。我相信它很困惑,因為您正在通過白天的標準時區。

    const zones = ["America/Los_Angeles", "America/Denver", "America/Chicago", "America/New_York"]
    zones.forEach(timeZone => 
    console.log(new Intl.DateTimeFormat('en-US', { timeZone, timeStyle: "full", dateStyle: "full"}).format(1588743894000)));

    這會產生:

    Tuesday, May 5, 2020 at 10:44:54 PM Pacific Daylight Time
    Tuesday, May 5, 2020 at 11:44:54 PM Mountain Daylight Time
    Wednesday, May 6, 2020 at 12:44:54 AM Central Daylight Time
    Wednesday, May 6, 2020 at 1:44:54 AM Eastern Daylight Time

    回覆
    0
  • 取消回覆