Javascript return number of days,hours,minutes,seconds between two dates
Does anyone can link me to some tutorial where I can find out how to return days , hours , minutes, seconds in javascript between 2 unix datetimes?
I have:
var date_now = unixtimestamp;
var date_future = unixtimestamp;
I would like to return (live) how many days,hours,minutes,seconds left from the date_now to the date_future.
Solution 1:
Just figure out the difference in seconds (don't forget JS timestamps are actually measured in milliseconds) and decompose that value:
// get total seconds between the times
var delta = Math.abs(date_future - date_now) / 1000;
// calculate (and subtract) whole days
var days = Math.floor(delta / 86400);
delta -= days * 86400;
// calculate (and subtract) whole hours
var hours = Math.floor(delta / 3600) % 24;
delta -= hours * 3600;
// calculate (and subtract) whole minutes
var minutes = Math.floor(delta / 60) % 60;
delta -= minutes * 60;
// what's left is seconds
var seconds = delta % 60; // in theory the modulus is not required
EDIT code adjusted because I just realised that the original code returned the total number of hours, etc, not the number of hours left after counting whole days.
Solution 2:
Here's in javascript: (For example, the future date is New Year's Day)
DEMO (updates every second)
var dateFuture = new Date(new Date().getFullYear() +1, 0, 1);
var dateNow = new Date();
var seconds = Math.floor((dateFuture - (dateNow))/1000);
var minutes = Math.floor(seconds/60);
var hours = Math.floor(minutes/60);
var days = Math.floor(hours/24);
hours = hours-(days*24);
minutes = minutes-(days*24*60)-(hours*60);
seconds = seconds-(days*24*60*60)-(hours*60*60)-(minutes*60);
Solution 3:
I call it the "snowman ☃ method" and I think it's a little more flexible when you need additional timespans like weeks, moths, years, centuries... and don't want too much repetitive code:
var d = Math.abs(date_future - date_now) / 1000; // delta
var r = {}; // result
var s = { // structure
year: 31536000,
month: 2592000,
week: 604800, // uncomment row to ignore
day: 86400, // feel free to add your own row
hour: 3600,
minute: 60,
second: 1
};
Object.keys(s).forEach(function(key){
r[key] = Math.floor(d / s[key]);
d -= r[key] * s[key];
});
// for example: {year:0,month:0,week:1,day:2,hour:34,minute:56,second:7}
console.log(r);
Have a FIDDLE / ES6 Version (2018) / TypeScript Version (2019)
Inspired by Alnitak's answer.