Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get timezone in 3 letters using momentjs?

I am getting timezones using following code using moment library

console.log(moment.tz.names())

Which gives me result in following format

0: "Africa/Abidjan"
1: "Africa/Accra"
2: "Africa/Addis_Ababa"
3: "Africa/Algiers"
4: "Africa/Asmara"
5: "Africa/Asmera"
6: "Africa/Bamako"

I need to get only abbreviations something like

enter image description here

Can moment gives such flexibility and also I need to get offsets as well?

Thank you!!!

like image 929
Profer Avatar asked Mar 04 '23 01:03

Profer


2 Answers

You can produce a companion list to the full zone names you get from moment.tz.names() by a quick .map():

let abbrs = moment.tz.names().map((z) => moment.tz(z).zoneAbbr());

For any zone object, .zoneAbbr() gives the zone abbreviation.

If you want the offsets, you can instead call .utcOffset():

let offsets = moment.tz.names().map((z) => moment.tz(z).utcOffset());

Or get both:

let zoneInfo = moment.tz.names().map((z) => {
  let zone = moment.tz(z);
  return {
    abbr: zone.zoneAbbr(),
    offset: zone.utcOffset()
  };
});
like image 82
Pointy Avatar answered Mar 16 '23 03:03

Pointy


You can use moment.format(string) to get abbreviation by passing z argument:

moment.tz(zone).format('z')

and offset by passing Z argument:

moment.tz(zone).format('Z')

console.log(
  moment.tz.names().forEach(zone => { 
    console.log( moment.tz(zone).format('Z z') ) 
  }) 
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.25/moment-timezone-with-data.min.js"></script>

Please note that the z formatting token will not always show the abbreviated time zone name, instead, will show the time offsets for each region and the same thing for moment#zoneAbbr.

like image 36
Fraction Avatar answered Mar 16 '23 02:03

Fraction