Search code examples
javascriptmomentjsmoment-timezone

How to retrieve current moment default time zone


If I set default moment time zone with moment.tz.setDefault(), is there a way to later retrieve the current default time zone?

Example:

const moment = require('moment-timezone');

moment.tz.setDefault('Asia/Tokyo');

console.log(moment.tz.getDefault()); // TypeError: moment.tz.getDefault is not a function
console.log(moment.tz.default);      // undefined
console.log(moment.tz.guess());      // America/New_York (my local timezone)
console.log(moment.tz.guess(true));  // America/New_York

// => I want something that will return "Asia/Tokyo"

This is different from the suggested duplicate because I don't want the browser's time zone, I specifically want to know what (if anything) moment.tz.setDefault() was set to.


Solution

  • You can achieve that by moment.defaultZone.name:

    const moment = require('moment-timezone');
    
    moment.tz.setDefault('Asia/Tokyo');
    
    console.log(moment.defaultZone.name)
    

    Output:

    Asia/Tokyo
    

    Update after @Kip comment

    • If no default time zone is set, moment.defaultZone is undefined, so use moment.defaultZone?.name to be safe.
    • Other approach which uses documented functionality is moment().format('ZZ') which returns "+0900" in Tokyo time.