HiveBrain v1.2.0
Get Started
← Back to all entries
gotchajavascriptCritical

Get difference between 2 dates in JavaScript?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
betweendifferencejavascriptgetdates

Problem

How do I get the difference between 2 dates in full days (I don't want any fractions of a day)

var date1 = new Date('7/11/2010');
var date2 = new Date('12/12/2010');
var diffDays = date2.getDate() - date1.getDate(); 
alert(diffDays)


I tried the above but this did not work.

Solution

Here is one way:



const date1 = new Date('7/13/2010');
const date2 = new Date('12/15/2010');
const diffTime = Math.abs(date2 - date1);
const diffDays = Math.floor(diffTime / (1000 60 60 * 24));
console.log(diffTime + " milliseconds");
console.log(diffDays + " days");




Observe that we need to enclose the date in quotes. The rest of the code gets the time difference in milliseconds and then divides to get the number of days. Date expects mm/dd/yyyy format.

Context

Stack Overflow Q#3224834, score: 1325

Revisions (0)

No revisions yet.