Search code examples
momentjsmoment-timezone

Moment timezone changes to local after I set it


I have a moment javascript code using timezones, and I'm trying to calculate a date relative to America/Chicago no matter where it is loaded. Then later I am showing a timespan that happens in America/Chicago relative to the user's local timezone.

http://jsfiddle.net/wdvy9za7

var d = moment("18:00", "HH:mm").tz("America/Chicago");

Line 31 is where I'm trying to set the date to be relative to America/Chicago. It doesn't matter what the date is what matters is that the time is 18:00. Later in the code Line 36 is where I get today's date to do a check on line 38

I'm trying to get the variable datenum to show the date number of today relative to America/Chicago no matter where the script is loaded.


Solution

  • When you convert from a moment to a Javascript Date using toDate(), you are losing the timezone information and creating a Date based on the timestamp of the original moment, so you'll get a Date corresponding to 18:00 in the local timezone. See more thorough explanation in this Github issue:

    The Date object has no time zone abilities other than working with the local time zone. We can't do anything about that. When you use toDate, any of moment or moment-timezone's ability to "represent" other time zones is stripped away. You're left with the raw instant in time represented by the timestamp [...]

    You might as well have just done moment(1493092800000).toDate() or moment.utc(1493092800000).toDate(). It's all the same as just new Date(1493092800000).

    You can instead keep the moment and use Moment's date() method:

    var d = moment("18:00", "HH:mm").tz("America/Chicago");
    var datenum = d.date();
    

    This will tell you what is the date locally, when it is 18:00 in Chicago.