Why moment-timezone does not apply given timezone

714 views Asked by At

I check moment in the Chrome Developer Tools on the moment-timezone website: https://momentjs.com/timezone/

I execute:

moment(new Date(2011, 9, 16, 12)).tz('America/Los_Angeles').toDate()

and the result is still:

Sun Oct 16 2011 12:00:00 GMT+0200 (Central European Daylight Time)

Why moment-timezone didn't apply given timezone and I get Central European Daylight Time?

1

There are 1 answers

2
AudioBubble On

When you create new Date(2011, 9, 16, 12), it gets October 16th 2011 at 12:00 in whatever the browser's timezone is. Then tz converts this to the specified timezone, and toDate() converts back to the date object (using the browser's timezone).

If you want to create October 16th 2011 at 12:00 in Los Angeles timezone, there's no need to use new Date. You can use moment.tz directly:

moment.tz('2011-10-16 12:00', 'America/Los_Angeles')

The output will be:

Sun Oct 16 2011 12:00:00 GMT-0700

You can also create the date passing values instead of a string (check the docs to see all options):

moment.tz([2011, 9, 16, 12], 'America/Los_Angeles')
moment.tz({ year: 2011, month: 9, day: 16, hour: 12 }, 'America/Los_Angeles')

All the above produce the same date (October 16th 2011 at 12:00 in Los Angeles timezone).

Note that the values are zero-indexed (January is zero), while in the string, months are 1-indexed (January is 1).


Calling toDate() on the above will convert the date/time to your browser's default timezone as well.