Please note that calculating only based on differences will not cover all cases: leap years and switching of "daylight savings time".
Javascript has poor built-in library for working with dates. I suggest you use a third party javascript library, e.g. MomentJS; you can see here the function you were looking for.
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.
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);
The best library that I know of for duration breakdown is countdown.js. It handles all the hard cases such as leap years and daylight savings as csg mentioned, and even allows you to specify fuzzy concepts such as months and weeks. Here's the code for your case:
//assuming these are in *seconds* (in case of MS don't multiply by 1000 below)
var date_now = 1218374;
var date_future = 29384744;
diff = countdown(date_now * 1000, date_future * 1000,
countdown.DAYS | countdown.HOURS | countdown.MINUTES | countdown.SECONDS);
alert("days: " + diff.days + " hours: " + diff.hours +
" minutes: " + diff.minutes + " seconds: " + diff.seconds);
//or even better
alert(diff.toString());
Here's a JSFiddle, but it would probably only work in FireFox or in Chrome with web security disabled, since countdown.js is hosted with a text/plain MIME type (you're supposed to serve the file, not link to countdownjs.org).
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);
Here is a code example. I used simple calculations instead of using precalculations like 1 day is 86400 seconds. So you can follow the logic with ease.
// Calculate time between two dates:
var date1 = new Date('1110-01-01 11:10');
var date2 = new Date();
console.log('difference in ms', date1 - date2);
// Use Math.abs() so the order of the dates can be ignored and you won't
// end up with negative numbers when date1 is before date2.
console.log('difference in ms abs', Math.abs(date1 - date2));
console.log('difference in seconds', Math.abs(date1 - date2) / 1000);
var diffInSeconds = Math.abs(date1 - date2) / 1000;
var days = Math.floor(diffInSeconds / 60 / 60 / 24);
var hours = Math.floor(diffInSeconds / 60 / 60 % 24);
var minutes = Math.floor(diffInSeconds / 60 % 60);
var seconds = Math.floor(diffInSeconds % 60);
var milliseconds = Math.round((diffInSeconds - Math.floor(diffInSeconds)) * 1000);
console.log('days', days);
console.log('hours', ('0' + hours).slice(-2));
console.log('minutes', ('0' + minutes).slice(-2));
console.log('seconds', ('0' + seconds).slice(-2));
console.log('milliseconds', ('00' + milliseconds).slice(-3));
here is an code to find difference between two dates in Days,Hours,Minutes,Seconds (assuming the future date is new year date).
var one_day = 24*60*60*1000; // total milliseconds in one day
var today = new Date();
var new_year = new Date("01/01/2017"); // future date
var today_time = today.getTime(); // time in miliiseconds
var new_year_time = new_year.getTime();
var time_diff = Math.abs(new_year_time - today_time); //time diff in ms
var days = Math.floor(time_diff / one_day); // no of days
var remaining_time = time_diff - (days*one_day); // remaining ms
var hours = Math.floor(remaining_time/(60*60*1000));
remaining_time = remaining_time - (hours*60*60*1000);
var minutes = Math.floor(remaining_time/(60*1000));
remaining_time = remaining_time - (minutes * 60 * 1000);
var seconds = Math.ceil(remaining_time / 1000);
var time = date_future - date_now;
var seconds = moment.duration(time).seconds();
var minutes = moment.duration(time).minutes();
var hours = moment.duration(time).hours();
var days = moment.duration(time).days();
/*Declare the function */
function Clock(){
let d1 = new Date("1 Jan 2021");
let d2 = new Date();
let difference = Math.abs(d1 - d2); //to get absolute value
//calculate for each one
let Days = Math.floor(difference / ( 1000 * 60 * 60 * 24 ));
let Hours = Math.floor((difference / ( 1000 * 60 * 60 )) % 24);
let Mins = Math.floor((difference / ( 1000 * 60 )) % 60);
let Seconds = Math.floor((difference / ( 1000 )) % 60);
//getting nodes and change the text inside
let getday = document.querySelector(".big_text_days");
let gethour = document.querySelector(".big_text_hours");
let getmins = document.querySelector(".big_text_mins");
let getsec = document.querySelector(".big_text_sec");
getday.textContent = Check_Zero(Days);
gethour.textContent = Check_Zero(Hours);
getmins.textContent = Check_Zero(Mins)
getsec.textContent = Check_Zero(Seconds);
}
//call the funcion for every 1 second
setInterval(Clock , 1000);
//check and add zero in front, if it is lessthan 10
function Check_Zero(mytime){
return mytime < 10 ? "0"+mytime : mytime;
}
Because MomentJS is quite heavy and sub-optimized, people not afraid to use a module should probably look at date-fns instead, which provides an intervalToDuration method which does what you want:
const result = intervalToDuration({
start: new Date(dateNow),
end: new Date(dateFuture),
})
A Little bit different flavour (maybe for some ppl more readable) it works in JavaScript and as little bonus it works in TypeScript as well.
If you make sure the first date is always greater than the second than you don't need the Math.abs() Also the round brackets around the modulo operation are unnecessary. I kept them for clearance.
let diffTime = Math.abs(new Date().valueOf() - new Date('2021-11-22T18:30:00').valueOf());
let days = diffTime / (24*60*60*1000);
let hours = (days % 1) * 24;
let minutes = (hours % 1) * 60;
let secs = (minutes % 1) * 60;
[days, hours, minutes, secs] = [Math.floor(days), Math.floor(hours), Math.floor(minutes), Math.floor(secs)]
console.log(days+'d', hours+'h', minutes+'m', secs+'s');