Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect timezone abbreviation using date-fns-tz?

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

like image 729
Devmix Avatar asked Dec 22 '20 21:12

Devmix


People also ask

Does date FNS support timezone?

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.

How can I get the timezone name in Javascript?

In javascript , the Date. getTimezoneOffset() method returns the time-zone offset from UTC, in minutes, for the current locale.


Video Answer


1 Answers

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

like image 142
antoniom Avatar answered Oct 28 '22 00:10

antoniom