Is there a way to represent the 21 october 2012 in

2019-06-22 05:27发布

I noticed something weird with timezones and Javascript Date object.

Trying this on a Linux box:

$ TZ='America/Sao_Paulo' js 
js> new Date(2012, 9, 21, 0, 0, 0).toString() 
"Sat Oct 20 2012 23:00:00 GMT-0300 (BRST)"

I found it impossible to get an object that represents the 21th of october 2012. Every attemps to get a Date between 00:00 and 01:00 that day results in a date the day before between 11:00 PM and 00:00.

(Windows user may change their timezone to Brasilia/GMT-03 to experience the same behavior)

Adding one hour (or one day) to such a date object results in getting back the same date.

I guess it has to do with daylight saving time which occurs on that specific date in Brazil, however I absolutely don't know how to deal with that.

I have a loop that iterates over the days of the month (for a calendar application) and it obviously loops forever in that case when reaching the 20th of october 2012.

There must be something I'm doing wrong, but I don't know how to deal with such a case, as I guess it could also happen for other timezones.

What is the recommended way of dealing with Date in Javascript to ensure that such timezone/daylight saving time related problems do not occur ?

1条回答
叛逆
2楼-- · 2019-06-22 06:17

This is an absolutely correct behavior. Due to the DST midnight simply does not exist in local time in Brazil on October 21st. If you just need to build a calendar you can just use new Date(2012, 9, 21, 0, 0, 0).toUTCString() instead of new Date(2012, 9, 21, 0, 0, 0).toString() and other UTC methods.

For example to create an UTC date you can use new Date(Date.UTC(2012, 9, 21, 0, 0, 0));.

查看更多
登录 后发表回答