Aug 2, 2023
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
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
So when you’ll get the proper
getHours(), take a look at what occurs if you use
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
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.
toLocaleString() perform that has good help for timezones.
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