I got two Date objects and I want to calculate the difference in hours.
If the difference in hours is less than 18 hours, I want to push the date object into an array.
Javascript / jQuery, doesn't really matter; what works the best will do.
This question is related to
javascript
jquery
date
object
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.
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); }
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
Source: Stackoverflow.com