Sometimes, we want to check time difference in JavaScript.
In this article, we’ll look at how to check time difference in JavaScript.
How to check time difference in JavaScript?
To check time difference in JavaScript, we can use the date getTime
method.
For instance, we write
const date1 = new Date("08/05/2022 23:41:20");
const date2 = new Date("08/06/2022 02:56:32");
const diff = date2.getTime() - date1.getTime();
let msec = diff;
const hh = Math.floor(msec / 1000 / 60 / 60);
msec -= hh * 1000 * 60 * 60;
const mm = Math.floor(msec / 1000 / 60);
msec -= mm * 1000 * 60;
const ss = Math.floor(msec / 1000);
msec -= ss * 1000;
to call getTime
to get the timestamp of the dates in milliseconds.
Then we get the difference of the timestamps.
Next, we get the hours with Math.floor(msec / 1000 / 60 / 60)
.
Then we subtract that from msec
and we use the new msec
value to get the minutes difference with Math.floor(msec / 1000 / 60)
.
Likewise, we use the same steps to get the seconds difference and we get the seconds difference with Math.floor(msec / 1000)
.
Conclusion
To check time difference in JavaScript, we can use the date getTime
method.