Search code examples
momentjsmoment-timezone

Moment misunderstanding utcOffset


I'm working with moment and moment-timezone and I don't get it. Can anyone explain me why this happens?

THIS (which is what I want):

moment('2018-11-28T00:00:00.000-02:00').toISOString()

Prints 2018-11-28T02:00:00.000Z

BUT:

moment('2018-11-28T00:00:00.000').zone('-02:00').toISOString()
moment('2018-11-28T00:00:00.000').utcOffset('-02:00').toISOString()

Both print 2018-11-27T23:00:00.000Z

PD: My zone is GMT+1.

Why are different? it is not supposed to be equals? How do I set the offset (not in the constructor but with a method after I have de moment object)?

Thanks! BR


Solution

  • As I can see, you want to keep the existing time of day when using utcOffset method. It accepts a second parameter, which is a boolean. As the documentation says:

    Passing true will keep the same local time, but at the expense of choosing a different point in Universal Time.

    // "2018-11-28T02:00:00.000Z"
    moment('2018-11-28T00:00:00.000').utcOffset('-02:00', true).toISOString();
    

    For more information check the documentation