2

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"
Alberto Rivera
  • 3,652
  • 3
  • 19
  • 33
  • You can just use `moment.tz()`, if I'm not mistaken. Otherwise there's [`moment.tz.guess()`](https://momentjs.com/timezone/docs/#/using-timezones/guessing-user-timezone/). – Heretic Monkey May 14 '20 at 17:38
  • `moment.tz()` creates a new moment object. `moment.tz.guess()` will return the timezone guessed from the browser. I will update the question with this attempt. I need the timezone currently set as default for moment-timezone (the one passed to `moment.tz.setDefault `). – Alberto Rivera May 14 '20 at 17:42

1 Answers1

2

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>
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • Pretty impressive! As you warned, probably it's something not to use (as it's undocumented and may disappear/change at any time), but it's a very interesting piece of information. – Alberto Rivera May 14 '20 at 18:49