To return a number of days, hours, minutes, and seconds between two dates with JavaScript, we can convert the start and end dates to timestamps.
Then we can calculate the number of days, hours, minutes, and seconds between two dates difference between the 2 dates.
For instance, we can write:
const dateFuture = new Date(2022, 1, 1, 1, 1, 1)
const dateNow = new Date(2021, 1, 1)
let delta = Math.abs(dateFuture - dateNow) / 1000;
const days = Math.floor(delta / 86400);
delta -= days * 86400;
const hours = Math.floor(delta / 3600) % 24;
delta -= hours * 3600;
const minutes = Math.floor(delta / 60) % 60;
delta -= minutes * 60;
const seconds = delta % 60
console.log(days, hours, minutes, seconds)
We have the dateFuture
and dateNow
date objects that we created with the Date
constructor.
Then we calculate the difference between them in seconds with:
let delta = Math.abs(dateFuture - dateNow) / 1000;
Then to get the numbers of days difference between them, we write:
const days = Math.floor(delta / 86400);
Then we get the hours difference with:
delta -= days * 86400;
const hours = Math.floor(delta / 3600) % 24;
We subtract the days
in seconds so that we can get the hours difference.
Similarly, we get the minutes with:
delta -= hours * 3600;
const minutes = Math.floor(delta / 60) % 60;
We subtract the hours
in seconds from the delta
to get the minutes
difference.
And then to get the seconds difference with:
delta -= minutes * 60;
const seconds = delta % 60
And we get that days
is 365, and hours
, minutes
, and seconds
are all 1.
Conclusion
To return a number of days, hours, minutes, and seconds between two dates with JavaScript, we can convert the start and end dates to timestamps.
Then we can calculate the number of days, hours, minutes, and seconds between two dates difference between the 2 dates.