Created
February 7, 2023 05:12
-
-
Save Risyandi/447ea5bfcbcd6522e75619165d4611a4 to your computer and use it in GitHub Desktop.
calculate the difference between current date (now) and given date.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** step by step | |
* 1. Get time that passed since Unix Epoch using Date() constructor with getTime(), | |
* 2. calculate the difference between current date and future date, | |
* 3. convert milliseconds to seconds, minutes, hours, etc. | |
* 4. calculate remaining time using modulo (%) operations and rounding the result using Math.floor() to get approximate result. | |
**/ | |
const now = new Date().getTime(); // current date | |
const futureDate = new Date('27 Jan 2030 16:40:00').getTime(); // setup time left | |
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'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
the reference article : https://dirask.com/posts/JavaScript-calculate-time-left-to-given-date-DlVdWj