Aug 2, 2023
Date-fns has a sibling library date-fns-tz that helps you’re employed with timezones in JavaScript, together with formatting dates in a selected timezone.
For instance, the next is how one can format a given date in Tahiti time with date-fns-tz:
const date = new Date('2023-08-02T12:00:00.000Z');
const formatInTimeZone = require('date-fns-tz');
formatInTimeZone(date, 'Pacific/Tahiti', 'yyyy-MM-dd HH:mma');
Changing to Totally different Timezones
Date-fns-tz additionally has a utcToZonedTime()
helper that converts a date that might render as the proper time when printed in JavaScript.
const date = new Date('2023-08-02T12:00:00.000Z');
const utcToZonedTime = require('date-fns-tz');
utcToZonedTime(date, 'Pacific/Tahiti').toString();
Nevertheless, we strongly advise in opposition to utilizing utcToZonedTime()
.
Discover that utcToZonedTime()
does not change the date’s timezone, within the above instance JavaScript nonetheless prints out “Japanese Daylight Time”, which is the timezone my laptop was in once I ran the above instance.
So when you’ll get the proper getHours()
, take a look at what occurs if you use toISOString()
:
utcToZonedTime(date, 'Pacific/Tahiti').toISOString();
The precise underlying time is completely different.
So when you use utcToZonedTime()
, you could be extraordinarily cautious to not cross the transformed date through JSON, since you’ll find yourself serializing the flawed time.
JSON.stringify( date: utcToZonedTime(date, 'Pacific/Tahiti') )
As an alternative of utilizing utcToZonedTime()
, retailer the time and the timezone you need to show, and use formatInTimeZone()
.
Vanilla JS Alternate options
Whereas we frequently use date-fns for comfort, you do not want date-fns to do primary duties like formatting dates in frequent timezones.
In fashionable JavaScript runtimes, dates have a toLocaleString()
perform that has good help for timezones.
Whereas there isn’t any formal specification for which timezones every runtime helps, we have not run right into a case the place a JavaScript runtime does not help a timezone that we need to use.
For instance, the next shows a given date in Ulaanbataar time.
const date = new Date('2023-08-02T08:00:00.000Z');
date.toLocaleString('en-US', timeZone: 'Asia/Ulaanbaatar' );
#Working #Timezones #datefns #datefnstz