moment-timezone change utc to default timezone

Viewed 1167

Context:

I need to parse datetimes from UTC into the timezone currently set as default by moment-timezone with moment.tz.setDefault.

Attempt (functional):

const task = {
    startDate: '2020-03-24 14:00:00'
};

const startDateMoment = moment.utc(task.startDate).tz(moment().tz());

However, I am creating a new moment object every time I need to set the timezone. Is there a more performant way to converting between utc to the default timezone, or getting the default timezone from moment?

moment.tz.guess() guesses the timezone from the browser, not the one set manually.

console.log(`default timezone: "${moment().tz()}", guessed timezone: "${moment.tz.guess()}"`);

returns

default timezone: "US/Samoa", guessed timezone: "America/Vancouver"
1 Answers

After a bit of digging, I did find the following, undocumented, use-at-your-own-risk, could-disappear-at-any-time property:

moment.defaultZone.name

moment.defaultZone is a Zone Object, of which we really only care about the name property.

Note that it is null if you haven't set a default yet! In the code below, I'm taking advantage of a couple new JavaScript features, optional chaining and the nullish coalescing operator to see if the default zone is set and if not, use the moment.tz.guess() value.

const task = {
    startDate: '2020-03-24 14:00:00'
};

console.log('before setting default: ', moment.defaultZone);

moment.tz.setDefault('US/Samoa');

console.log('after setting default: ', moment.defaultZone);

const startDateMoment = moment.utc(task.startDate).tz(moment.defaultZone?.name ?? moment.tz.guess());

console.log(startDateMoment.format());
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.min.js"></script>

Related