gotchajavascriptMajor
Timezone-Aware Date Display Using Intl.DateTimeFormat
Viewed 0 times
timezoneIntl.DateTimeFormat timezoneUTC date displayIANA timezoneuser timezonedate formatting timezone
Problem
Dates stored in UTC display incorrectly for users in different timezones because rendering code does not specify a timezone, defaulting to the server's or user's system timezone unpredictably.
Solution
Always pass an explicit
timeZone option to Intl.DateTimeFormat. Get the user's IANA timezone from the browser and use it for all date formatting.// Get user's timezone (browser)
const userTZ = Intl.DateTimeFormat().resolvedOptions().timeZone;
// e.g., 'America/New_York', 'Europe/Paris', 'Asia/Tokyo'
const date = new Date('2024-12-31T15:00:00Z');
new Intl.DateTimeFormat('en-US', {
timeZone: 'America/New_York',
dateStyle: 'full',
timeStyle: 'short',
}).format(date);
// 'Tuesday, December 31, 2024 at 10:00 AM'
new Intl.DateTimeFormat('en-US', {
timeZone: 'Asia/Tokyo',
dateStyle: 'full',
timeStyle: 'short',
}).format(date);
// 'Wednesday, January 1, 2025 at 12:00 AM'Why
Server-rendered HTML that formats dates without a timezone uses the server's system timezone. A date formatted as
Dec 31 on a UTC server becomes Jan 1 for a Tokyo user — an off-by-one-day error that is invisible in local testing.Gotchas
- Never format dates on the server without knowing the user's timezone — pass it in a cookie, header, or user profile.
new Date('2024-12-31')(date-only string) is parsed as UTC midnight, butnew Date('2024-12-31T00:00:00')(no Z) is parsed as local time — always use explicit ISO 8601 with timezone offset.- DST transitions can cause dates to appear to jump an hour — always store and transmit timestamps in UTC.
- The
timeZoneoption accepts IANA timezone identifiers (America/New_York), not offset strings like+05:30.
Revisions (0)
No revisions yet.