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
Can moment gives such flexibility and also I need to get offsets as well?
Thank you!!!
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()
};
});
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
.
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