Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why these date setDate( day+1 ) not adding 24 hours?

Tags:

javascript

[Please help me improve the title if it doesn't describe the question clear]


I found this weird thing when I develop a jquery plugin:

var a = new Date('1986-05-03');
a.setHours(0,0,0,0);
// a = Sat May 03 1986 00:00:00 GMT+0800 (CST)

a.setDate( a.getDate() + 1 );
// a = Sat May 03 1986 23:00:00 GMT+0800 (CST)

It actually adds 23 hours

There's some other ticket mentioned daylight savings, but May 3 is not the beginning of daylight saving days, right ?

Further, I tried to print all the not-24-hours date, here's my code:

var start = new Date('1900-01-01'); // FYI, IE8- doesn't support this kind of date construction
var end = new Date('2014-01-01');
start.setHours(0,0,0,0);
end.setHours(0,0,0,0);

while (start.getTime() < end.getTime()) {
    var oneMoreDay = new Date(start.getTime()); 
    oneMoreDay.setDate(start.getDate() + 1);
    var diff = oneMoreDay.getTime() - start.getTime();
    if (diff != 86400000) {
        console.log(start);
    }
    start = oneMoreDay;
} 

Here's the output:

Sat May 03 1986 23:00:00 GMT+0800 (CST) VM124:12
Fri Sep 12 1986 23:00:00 GMT+0900 (CST) VM124:12
Sat Apr 11 1987 23:00:00 GMT+0800 (CST) VM124:12
Fri Sep 11 1987 23:00:00 GMT+0900 (CST) VM124:12
Sat Apr 09 1988 23:00:00 GMT+0800 (CST) VM124:12
Fri Sep 09 1988 23:00:00 GMT+0900 (CST) VM124:12
Sat Apr 15 1989 23:00:00 GMT+0800 (CST) VM124:12
Fri Sep 15 1989 23:00:00 GMT+0900 (CST) VM124:12
Sat Apr 14 1990 23:00:00 GMT+0800 (CST) VM124:12
Fri Sep 14 1990 23:00:00 GMT+0900 (CST) VM124:12
Sat Apr 13 1991 23:00:00 GMT+0800 (CST) VM124:12
Fri Sep 13 1991 23:00:00 GMT+0900 (CST) 

So, it's not in every year! Why are these date special?

like image 227
Phoenix Avatar asked Mar 20 '23 21:03

Phoenix


1 Answers

It is every April/May and September and it gives you a different GMT offset. That is daylight savings.

From Wikipedia:

After the Chinese Civil War, in 1949, a unified time zone—GMT+8—was established by the People's Republic of China for all its territories, called Beijing Time (sometimes known as Chinese Standard Time). Daylight saving time was observed from 1986 to 1991.

It isn't a problem. The time is correct. The time offset just changes. Ignore it, all calculation will work correctly.

P.S. That is the first time I had to research the Chinese Civil War for stack overflow.

like image 174
Damien Black Avatar answered Apr 02 '23 20:04

Damien Black