EN
JavaScript - calculate time left to given date
0
points
In this article, we would like to show you how to calculate time left to given date in JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
const now = new Date().getTime();
const futureDate = new Date('27 Jan 2030 16:40:00').getTime();
const timeleft = futureDate - now;
const days = Math.floor( timeleft / (1000 * 60 * 60 * 24));
const hours = Math.floor((timeleft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((timeleft % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((timeleft % (1000 * 60)) / 1000);
console.log(days + ' days ' + hours + ' hours ' + minutes + ' minutes ' + seconds + ' seconds left');
Practical example
In this example, we calculate the difference between current date (now
) and given date in three steps:
- Get time that passed since Unix Epoch using
Date()
constructor withgetTime()
, - calculate the difference between current date and future date,
- convert milliseconds to seconds, minutes, hours, etc.
- calculate remaining time using modulo (
%
) operations and rounding the result usingMath.floor()
to get approximate result.
Runnable example:
// ONLINE-RUNNER:browser;
const now = new Date().getTime();
const futureDate = new Date('27 Jan 2030 16:40:00').getTime();
const timeleft = futureDate - now;
// convert milliseconds to seconds / minutes / hours etc.
const msPerSecond = 1000;
const msPerMinute = msPerSecond * 60;
const msPerHour = msPerMinute * 60;
const msPerDay = msPerHour * 24;
// calculate remaining time
const days = Math.floor(timeleft / msPerDay);
const hours = Math.floor((timeleft % (1000 * 60 * 60 * 24)) / msPerHour);
const minutes = Math.floor((timeleft % (1000 * 60 * 60)) / msPerMinute);
const seconds = Math.floor((timeleft % (1000 * 60)) / msPerSecond);
console.log(days + ' days ' + hours + ' hours ' + minutes + ' minutes ' + seconds + ' seconds left');