1

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?

Yoda
  • 17,363
  • 67
  • 204
  • 344
  • 1
    Just a thought... You are using moment.js so you don't need to deal with `Date` oddities. If you feed it with `new Date(2011, 9, 16, 12)` you're defeating the overall purpose. – Álvaro González Aug 29 '17 at 12:15
  • Have you added time zone list to moment.tz object? – Ankit Solanki Aug 29 '17 at 12:23
  • @AnkitSolanki I didn't, they did, I am no the author of https://momentjs.com/timezone/ – Yoda Aug 29 '17 at 12:24
  • if you have import moment js file without timezone then you have to add all time zone then this can works. – Ankit Solanki Aug 29 '17 at 12:26
  • 1
    This is *close* to [this question](https://stackoverflow.com/questions/29618728/momentjs-how-to-get-the-date-in-a-specific-timezone), though not exact duplicate so I'll keep this one open. Still, you should read. Thanks. – Matt Johnson-Pint Aug 29 '17 at 18:39

1 Answers1

1

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.

  • 3
    Keep in mind this creates a `moment` object. From there, one should still use a function like `format` to get the desired output. – Matt Johnson-Pint Aug 29 '17 at 18:34
  • @MattJohnson Indeed! But as the OP didn't specify that they want the date in a specific format, I didn't include that in the question. But thanks for reminding! –  Aug 29 '17 at 18:35