Sometimes, we want to get the time difference between 2 dates in seconds with JavaScript.
In this article, we’ll look at how to get the time difference between 2 dates in seconds with JavaScript.
Convert the Dates to Timestamps in Milliseconds Then Get the Difference Between Them and Convert the Difference to Seconds
We can convert the dates to timestamps in milliseconds.
Then we can subtract them to get the difference between them.
And then we can convert the difference in milliseconds to seconds.
For instance, we can write:
const startDate = new Date(2020, 1, 1);
const endDate = new Date(2020, 2, 1);
const seconds = (endDate.getTime() - startDate.getTime()) / 1000;
console.log(seconds)
We have the startDate
and endDate
which we can convert both to timestamps in milliseconds with getTime
.
Then we subtract the timestamp of endDate
by the timestamp of startDate
.
This will return the timestamp difference in milliseconds.
So we divide the difference by 1000 to get the difference in seconds.
Therefore, seconds
should be 2505600
.
We can replace getTime
with the unary +
operator.
For instance, we can write:
const startDate = new Date(2020, 1, 1);
const endDate = new Date(2020, 2, 1);
const seconds = (+endDate - +startDate) / 1000;
console.log(seconds)
to convert startDate
and endDate
to timestamps with the unary +
operator.
And we get the same result as before.
Conclusion
We can get the time difference between 2 dates in seconds by converting them both to timestamps.
Then we can subtract the timestamps and convert the difference to seconds.