dmck
dmck

Reputation: 7861

Calculating number of days that occur between two Dates

I'm looking for the most succinct solution to the following problem in JavaScript:

I want to determine the number of days that occur between two Dates in JavaScript. I am not looking for the date difference in Days, for example:

Date 1: June 26th 2012 11:05 PM

Date 2: June 27th 2012 12:15 AM

I was using the the following line of code:

var days = Math.ceil((date2 - date1) / 86400000);

My result is 1, I want it to be 2 (counting June 26th and June 27th)

Upvotes: 1

Views: 992

Answers (2)

Matt Dodge
Matt Dodge

Reputation: 11142

Remove the time portion of the date and then do the date subtraction. See this jsfiddle or the snippet below.

var d1 = new Date('June 26th 2012 11:05 PM'.replace('th',''));
var d2 = new Date('June 27th 2012 12:15 AM'.replace('th',''));

// remove the time portion, set the dates to midnight
d1.setHours(0,0,0,0);
d2.setHours(0,0,0,0);

var diff = Math.ceil((d2 - d1) / 86400000) + 1;

console.log(diff);

Upvotes: 3

Joe
Joe

Reputation: 8042

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date

Set the hours, minutes, seconds, and miliseconds to all be zero. Now you have two dates with the same time on them. Now you can do that operation the way you have been doing it and get the right answer.

Upvotes: 1

Related Questions