Skip to content

Instantly share code, notes, and snippets.

@Risyandi
Created February 7, 2023 05:12
Show Gist options
  • Save Risyandi/447ea5bfcbcd6522e75619165d4611a4 to your computer and use it in GitHub Desktop.
Save Risyandi/447ea5bfcbcd6522e75619165d4611a4 to your computer and use it in GitHub Desktop.
calculate the difference between current date (now) and given date.
/** 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');
@Risyandi
Copy link
Author

Risyandi commented Feb 7, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment