EN
JavaScript - get hours difference between two date objects
1 answers
0 points
I've got two Date
objects and I want to calculate the difference between them in hours.
How can I do that?
1 answer
0 points
Quick solution:
xxxxxxxxxx
1
Math.abs(date1 - date2) / (1000 * 60 * 60);
Practical example
Using Math.abs()
you can get the absolute difference between two dates in milliseconds. Then you need to divide the difference by number of milliseconds in 1 hour (1000 * 60 * 60
).
xxxxxxxxxx
1
var date1 = new Date('2022-10-20T00:00:00.000Z');
2
var date2 = new Date('2022-10-21T00:00:00.000Z');
3
4
var difference = Math.abs(date1 - date2); // absolute difference between dates (in milliseconds)
5
6
var hour = 1000 * 60 * 60; // milliseconds for one hour
7
8
var result = difference / hour; // result - difference in hours
9
10
console.log(result); // 24
References
0 commentsShow commentsAdd comment