I want to print timeZone abbreviation like: IST, UTC, PST, MST, CST, EST, etc...
I'm migrating my code from momentJS to date-fns and having the following issue. When I was using momentJS everything was working as expected. For example, the code below will print "IST"
const timeZone = 'Asia/Calcutta';
moment.tz(new Date(), timeZone).format('z'); // IST
Demo using MomentJS
Now my code using date-fns works but not all the way because it prints "India Standard Time" and I only want to print IST.
format(parisDate, 'zzzz', { timeZone: 'Asia/Calcutta', locale: enGB }); // India Standard Time
Can anyone tell me what I'm missing or doing wrong? Here's a live demo of my code: date-fns DEMO
Date-fns supports time zone data to work with UTC or ISO date strings. This will help you display the date and time in the local time of your users. The difficulty comes when working with another time zone's local time, for example showing the local time of an event in LA at 8 pm PST on a Node.
In javascript , the Date. getTimezoneOffset() method returns the time-zone offset from UTC, in minutes, for the current locale.
After examining the date-fns-tz
's code it turns out that it does not generate the timezone abbreviation's by itself but it uses the browser's Intl API. Timezone abbreviations differ from locale to locale.
Locales such as 'en-US' or 'en-GB' do not include IST as timezone abbreviation while 'en-IN' does.
You therefore need to
import enIN from 'date-fns/locale/en-IN'
and then pass it as a 3rd agument on your format
call
i.e.
import { utcToZonedTime, format } from "date-fns-tz";
const timeZone = "Asia/Kolkata"
const zoneString = format(utcToZonedTime(new Date(), timeZone), "zzz", {
timeZone,
locale: enIN
});
This however does not guarantee that other abbreviations (e.g. CET) will work with the proposed locale
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With