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:
xxxxxxxxxx
1
const now = new Date().getTime();
2
const futureDate = new Date('27 Jan 2030 16:40:00').getTime();
3
4
const timeleft = futureDate - now;
5
6
const days = Math.floor( timeleft / (1000 * 60 * 60 * 24));
7
const hours = Math.floor((timeleft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
8
const minutes = Math.floor((timeleft % (1000 * 60 * 60)) / (1000 * 60));
9
const seconds = Math.floor((timeleft % (1000 * 60)) / 1000);
10
11
console.log(days + ' days ' + hours + ' hours ' + minutes + ' minutes ' + seconds + ' seconds left');
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:
xxxxxxxxxx
1
const now = new Date().getTime();
2
const futureDate = new Date('27 Jan 2030 16:40:00').getTime();
3
4
const timeleft = futureDate - now;
5
6
// convert milliseconds to seconds / minutes / hours etc.
7
const msPerSecond = 1000;
8
const msPerMinute = msPerSecond * 60;
9
const msPerHour = msPerMinute * 60;
10
const msPerDay = msPerHour * 24;
11
12
// calculate remaining time
13
const days = Math.floor(timeleft / msPerDay);
14
const hours = Math.floor((timeleft % (1000 * 60 * 60 * 24)) / msPerHour);
15
const minutes = Math.floor((timeleft % (1000 * 60 * 60)) / msPerMinute);
16
const seconds = Math.floor((timeleft % (1000 * 60)) / msPerSecond);
17
18
console.log(days + ' days ' + hours + ' hours ' + minutes + ' minutes ' + seconds + ' seconds left');