moment().toISOString() bug, if you pass in a 18th, it returns 17th

Created on 23 Jul 2013  ·  6Comments  ·  Source: moment/moment

This problem seems to be caused by moment().toISOString() introduced here:

http://momentjs.com/docs/#/displaying/as-iso-string/
moment().toISOString();

I might but in the console if I do:

    n = moment.utc(new Date('2013-07-18T00:00:00+01:00'))

It will return:

 Thu Jul 18 2013 00:00:00 GMT+0100 (GMT Daylight Time)

Now if I call toISOString() on it, the date suddenly becomes 17th:

  n.toISOString()

the above will return the 17th instead of 18th:

  "2013-07-17T23:00:00.000Z"

Most helpful comment

That might work for you then:

> moment().format('YYYY-MM-DD[T]HH:mm:ss.SSSZZ')
'2013-07-23T14:54:20.176-0700'

Or

> moment().format('YYYY-MM-DD[T]HH:mm:ss.SSS')
'2013-07-23T14:54:20.176'

If you don't care about the timezone, and just want to display the time.

All 6 comments

As you can see toISOString always displays the time in UTC (in addition to displaying it in a specific way).

@ichernev , I don't fully get your point? Does displaying in specific ways means when I pass in 17th, I should get 18th? How do I pass in 18th and get back 18th? thanks.

That might work for you then:

> moment().format('YYYY-MM-DD[T]HH:mm:ss.SSSZZ')
'2013-07-23T14:54:20.176-0700'

Or

> moment().format('YYYY-MM-DD[T]HH:mm:ss.SSS')
'2013-07-23T14:54:20.176'

If you don't care about the timezone, and just want to display the time.

@ichernev, many thanks.

You can use keepOffset parameter of toISOString:

toISOString(keepOffset?: boolean): string;

=>

moment().toISOString(true)

Is this really right?

moment('1970-01-01').toISOString()

outputs:

1969-12-31T23:00:00.000Z

I think most people passing in a specific date to moment and formatting it as an toISOString would expect the date to not change. Why doesn't keepOffset default to true if it makes the function behave in a more predictable manner?

I know moment are being consistant with the native JavaScript Date toISOString function as per ES2015 but even so this just doesn't feel like expected behaviour.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

RobinvanderVliet picture RobinvanderVliet  ·  3Comments

chitgoks picture chitgoks  ·  3Comments

IbraheemAlSaady picture IbraheemAlSaady  ·  3Comments

4rg0n picture 4rg0n  ·  3Comments

danieljsinclair picture danieljsinclair  ·  3Comments