How to get the hours difference between two date objects? [duplicate]
Solution 1:
The simplest way would be to directly subtract the date objects from one another.
For example:
var hours = Math.abs(date1 - date2) / 36e5;
The subtraction returns the difference between the two dates in milliseconds. 36e5
is the scientific notation for 60*60*1000
, dividing by which converts the milliseconds difference into hours.
Solution 2:
Try using getTime
(mdn doc):
var diff = Math.abs(date1.getTime() - date2.getTime()) / 3600000;
if (diff < 18) { /* do something */ }
Using Math.abs()
we don't know which date is the smallest. This code is probably more relevant:
var diff = (date1 - date2) / 3600000;
if (diff < 18) { array.push(date1); }
Solution 3:
Use the timestamp you get by calling valueOf
on the date object:
var diff = date2.valueOf() - date1.valueOf();
var diffInHours = diff/1000/60/60; // Convert milliseconds to hours