英文:
how can I use Intl.dateTimeFormat to display the value of a timestamp across four time zones in standard time?
问题
这输出:
星期二,2020年5月5日,晚上10:44:54 太平洋夏令时间
星期二,2020年5月5日,晚上10:44:54 GMT-07:00
星期三,2020年5月6日,凌晨12:44:54 中央夏令时间
星期三,2020年5月6日,凌晨12:44:54 GMT-05:00
但这不应该是四个不同的值吗?
英文:
I have timestamps that I'd like to be able to display in a user given time zone. I'm noticing that even when using a dedicated library like date-fns-tz it seems to return values that don't make sense.
Under the hood they apparently use Intl, and when I use that module it doesn't seem to provide the correct value.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const zones = ['PST', 'MST', 'CST', 'EST'];
zones.forEach((timeZone) =>
console.log(
new Intl.DateTimeFormat('en-US', {
timeZone,
timeStyle: 'full',
dateStyle: 'full',
}).format(1588743894000)
)
);
<!-- end snippet -->
This outputs:
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
But shouldn't this be four different values?
答案1
得分: 2
你正在指定三个字母的时区缩写,但它期望的是一个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
英文:
You are specifying the three-letter timezone abbreviations, what it is expecting is an IANA timezone (https://tc39.es/ecma402/#sec-time-zone-names). I believe it is flummoxed because you're passing standard timezones for a daylight time.
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)));
This yields:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论