Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Date bug on 31 june?

I am trying to check a dates form and I am having the following problem: date difference between 2014-06-30 and 2014-07-01 is two days. Here is a simplified part of my test code :

var date1 = (new Date(2012, 06, 30)).getTime();
var date2 = (new Date(2012, 07, 01)).getTime();
console.log(Math.round((date2-date1)/(1000.0*60*60*24)));

The result is "2". It gives me 1 only if I set date1 to (2014, 06, 31) But you know June is only 31 days! The result is the same event if I change Year to 2012, 2013...

like image 602
blt soft Avatar asked Mar 09 '26 14:03

blt soft


2 Answers

Months start at 0 as the documentation of the Date object explains:

Integer value representing the month, beginning with 0 for January to 11 for December.

So new Date(2012, 06, 30) is not June as you might think. This is July. That's why it has 31 days.

In your example you are calculating the date difference between 1st of August and 30th of July which as your calculus indicates is 2 days.

If you wanted to calculate the day difference between 1st of July and 30th of June:

var date1 = (new Date(2012, 05, 30)).getTime();
var date2 = (new Date(2012, 06, 01)).getTime();
console.log(Math.round((date2-date1)/(1000.0*60*60*24)));
like image 65
Darin Dimitrov Avatar answered Mar 12 '26 03:03

Darin Dimitrov


new Date(2012, 06, 30) is July, not June.

Try it in your JavaScript console:

> new Date(2012, 06, 30) 
Mon Jul 30 2012 00:00:00 GMT-0400 (EDT)
> new Date(2012, 06, 31) 
Tue Jul 31 2012 00:00:00 GMT-0400 (EDT)
like image 32
meagar Avatar answered Mar 12 '26 03:03

meagar