Borislav Hadzhiev
Mon Jan 17 2022·2 min read
Photo by Akhil Dakinedi
To get the number of hours between 2 dates:
1000 * 60 * 60
.function getHoursDiff(startDate, endDate) { const msInHour = 1000 * 60 * 60; return Math.round(Math.abs(endDate - startDate) / msInHour); } // 👇️ (9 hours - 6 hours = 3 hours) console.log( getHoursDiff( new Date(2022, 1, 24, 6, 44, 0), new Date(2022, 1, 24, 9, 45, 30), ), ); // 👇️ (1 day - 0 hours = 24 hours) console.log( getHoursDiff( new Date(2022, 1, 23, 9, 40, 0), new Date(2022, 1, 24, 9, 45, 0), ), );
The parameters we passed to the Date()
constructor in the examples are -
year
, month
(0 = January, 1 = February, etc), day of the month
, hour
,
minutes
and seconds
.
We created a reusable function that returns the number of hours between 2 dates.
The msInHour
variable stores the number of milliseconds there are in an hour.
We could have called the getTime()
method on both of the Date
objects to
achieve the same result.
function getHoursDiff(startDate, endDate) { const msInHour = 1000 * 60 * 60; return Math.round( Math.abs(endDate.getTime() - startDate.getTime()) / msInHour, ); } // 👇️ (9 hours - 6 hours = 3 hours) console.log( getHoursDiff( new Date(2022, 1, 24, 6, 44, 0), new Date(2022, 1, 24, 9, 45, 30), ), ); // 👇️ (1 day - 0 hours = 24 hours) console.log( getHoursDiff( new Date(2022, 1, 23, 9, 40, 0), new Date(2022, 1, 24, 9, 45, 0), ), ); console.log(new Date().getTime()); // 👉️ 164243142779
In the example, we called the getTime()
method to explicitly convert the
Date
object to a timestamp when subtracting.
This might be the more clear and explicit approach for readers of your code.
We used the Math.abs function to handle a scenario where we subtract a greater timestamp from a smaller one.
The Math.abs
function returns the absolute value of a number. In other words,
if the number is positive, the number is returned and if the number is negative,
the negation of the number is returned.
console.log(Math.abs(-3)); // 👉️ 3 console.log(Math.abs(3)); // 👉️ 3
We passed the value to the Math.round function to round to the nearest integer.
Here are some examples of how the Math.round
function works.
console.log(Math.round(2.49)); // 👉️ 2 console.log(Math.round(2.5)); // 👉️ 3
The function rounds the number up or down to the nearest integer.
0.5
, it gets rounded to the next higher absolute value.If the number is positive and its fractional portion is less than 0.5
, it gets
rounded to the lower absolute value.