Search code examples
timezonemomentjsutcdsttimezone-offset

UTC date from different daylight savings adjusted for current timezone


I have dates saved in mongodb in UTC format, e.g. "2016-01-28T00:00:00.000Z". In the client I am using moment.js to format the date. However, when I created a moment of this particular date, daylight savings comes into play:

>moment("2016-01-28T00:00:00.000Z").format()

"2016-01-27T19:00:00-05:00"

If I use moment's timezone to adjust this time, it will not work because the offset is -4 at the moment, not -5. What is the correct way to adjust this time, such that instead of 1/27/16, I get 1/28/16, which is what i want. At the moment, one solution I though of what to get the .utcOffset in minutes and add this to the moment of my time:

moment("2016-01-28T00:00:00.000Z").add( -moment("2016-01-28T00:00:00.000Z").utcOffset(),'minutes').format()

"2016-01-28T00:00:00-05:00"

However, I am not sure if this is the best way of doing this.


Solution

  • Check out the specification for ISO 8601, specifically surrounding the timezone designators.

    The "Z" at the end of the formatted input string designates the number as being in the UTC timezone. The moment library takes the UTC date and automatically converts it to the local timezone, which in your case means subtracting a few hours off.

    If you take the "Z" off, then moment will interpret it as an "unspecified" time zone, and will not add or subtract any time from the given datetime. So note:

    > moment("2016-01-28T00:00:00.000Z").format()
    < "2016-01-27T19:00:00-05:00"
    > moment("2016-01-28T00:00:00.000").format()
    < "2016-01-28T00:00:00-05:00"
    

    After removing the "Z", moment will still format the new date with -05:00 as the timezone designator, but won't modify the datetime.