Strange behavior. Date.js date

We are tracking a bug in our application, which is apparently related to the formatting of the .js moment.

Here's the problematic call (reproduced in Chrome, FF, and Edge for reference):

moment('2016-03-13T23:59:59.999-06:00').format('YYYY-MM-DD') 

What do we expect:

2016-03-13

What do we get:

2016-03-14

This, apparently, has something to do with daylight saving time, as this is the only date (so far) that we were able to reproduce this incorrect behavior, and DST turned over on that day.

If we replace UTC offset with -05:00 , then it will work correctly.

Here's a simple jsbin for demonstrating

What's going on here? How can we solve this?

+5
source share
4 answers

Moment converts the offset date to the local time zone of the computer you are on if you use the default constructor function.

For this reason, your code is working as expected. The date is taken from -6 and converted to a local offset.

If you want to use the date in the specified time zone offset, use the moment.parseZone parameter:

 moment.parseZone('2016-03-13T23:59:59.999-06:00').format() "2016-03-13T23:59:59-06:00" 

If you want to ignore the time zone offset and work in local time, specify a format that does not include the offset. By doing this, you cause displacement to be ignored.

 moment('2016-03-13T23:59:59.999-06:00', 'YYYY-MM-DDTHH:mm:ss.SSS').format() "2016-03-13T23:59:59-05:00" 

Please note that I am in UTC-5 and the offset is displayed as -5 because I ignored the offset in the date.

A parsing guide can help: http://momentjs.com/guides/#/parsing/

+4
source

In the momentjs documentation regarding parsing time zones , they show that in order to account for the specified time zone in the input line, you should use moment.parseZone() .

 console.log(moment.parseZone('2016-03-13T23:59:59.999-06:00').format('YYYY-MM-DD')); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.min.js"></script> 

The above output is "2016-03-13" on the console for me.

+3
source

You specify the time zone for encoding (-6), but you rely on the client time zone for formatting. The difference is the culprit.

+2
source

In principle, there is nothing wrong with the function of the format of the moment. console.log(moment.utc('2016-03-13T23:59:59.999-06:00').toString()); console.log(moment('2016-03-13T23:59:59.999-06:00').toString());

If you try to execute both of the above lines, you will see that moment.utc() basically removes the offset and converts it to a timestamp in UTC format, not just the date and moment() translates the -06: 00 offset to your local time belt, and if you have less bias, you basically get the wrong date due to time.

Hope I helped.

0
source

Source: https://habr.com/ru/post/1245584/


All Articles