How to get the hours difference between two date objects?

JavascriptJqueryDateObject

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnoniem AnoniemView Question on Stackoverflow
Solution 1 - JavascriptBoazView Answer on Stackoverflow
Solution 2 - Javascriptuser1636522View Answer on Stackoverflow
Solution 3 - JavascriptMatt ZeunertView Answer on Stackoverflow