Last active
May 6, 2022 17:48
-
-
Save nfreear/10c528b4971b6db1031ab56e7c850624 to your computer and use it in GitHub Desktop.
Calculate countdown in days, hours, minutes and seconds | https://geeksforgeeks.org/create-countdown-timer-using-javascript/
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
/** | |
* Calculate countdown in days, hours, minutes and seconds. | |
* | |
* @author Nick Freear, 06-May-2022. | |
* | |
* @see https://geeksforgeeks.org/create-countdown-timer-using-javascript/ | |
*/ | |
console.log('Countdown:', calcCountdown('2022-05-19')); | |
console.log('Countdown:', calcCountdown('dec 31, 2022 00:00:00.000 ')); | |
console.log('Countdown:', calcCountdown('19/05/2022')); // Throws error! | |
function calcCountdown (deadlineStr) { | |
const deadline = new Date(deadlineStr).getTime(); | |
const now = new Date().getTime(); | |
const diff = deadline - now; | |
if (isNaN(deadline)) { | |
throw new Error(`Input not recognized as a date-time: '${deadlineStr}'`); | |
} | |
const days = Math.floor(diff / (1000 * 60 * 60 * 24)); | |
const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); | |
const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)); | |
const seconds = Math.floor((diff % (1000 * 60 )) / 1000); | |
return { days, hours, minutes, seconds, deadline: deadlineStr, diff, expired: diff < 0 }; | |
} | |
// End. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment