Reputation: 1858
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
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
Upvotes: 9
Views: 9353
Reputation: 3241
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
Upvotes: 4