Home > Software engineering >  How to convert time zone id to to time zone name in js or moment.js
How to convert time zone id to to time zone name in js or moment.js

Time:11-26

How to convert time zone id to to time zone name by moment-timezone.js

Example:

const timeZone = moment.tz('America/Mexico_City');
timeZone.zoneAbbr() // CST to Central Standard Time
timeZone.format('z') // CST to Central Standard Time

I need to have Central Standard Time

CodePudding user response:

If you are considering using plain ole JavaScript as an alternative, simply use the Intl.DateTimeFormat() to control any aspect of a date or time display.

Like this:

const time = new Intl.DateTimeFormat("en" , {timeZoneName: "long"});
let date = new Date();
console.log(time.format(date));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Using moment, you need to override the zoneName function, to use zz token.

Ref - https://momentjs.com/timezone/docs/#/using-timezones/formatting/

const timeZone = moment().tz('America/Mexico_City');

var abbrs = {
    EST : 'Eastern Standard Time',
    EDT : 'Eastern Daylight Time',
    CST : 'Central Standard Time',
    CDT : 'Central Daylight Time',
    MST : 'Mountain Standard Time',
    MDT : 'Mountain Daylight Time',
    PST : 'Pacific Standard Time',
    PDT : 'Pacific Daylight Time',
};

moment.fn.zoneName = function () {
    var abbr = this.zoneAbbr();
    return abbrs[abbr] || abbr;
};

console.log(timeZone.format('zz'));
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.js"></script>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You could use Date.toLocaleTimeString() to get the timezone name (either long or short style):

function getTimeZoneName(timeZone, timeZoneName = 'short') {
    let [,...tz] = new Date().toLocaleTimeString('en', { timeZoneName: "long", timeZone, timeZoneName, hour12: false }).split(' ');
    return tz.join(' '); 
}

let timeZones = ['America/Mexico_City', 'America/Los_Angeles', 'Europe/Berlin'];
for(let timeZone of timeZones) {
    console.log('\nTimezone:', timeZone);
    console.log('Long/Short name:', getTimeZoneName(timeZone, 'long'), '/', getTimeZoneName(timeZone, 'short'));
}
    
.as-console-wrapper { max-height: 100% !important; top: 0; }
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related