Skip to content

Instantly share code, notes, and snippets.

@jimdiroffii
Created March 15, 2025 22:02
Show Gist options
  • Save jimdiroffii/2c1d28d9119012019ed42f1a6798f5ce to your computer and use it in GitHub Desktop.
Save jimdiroffii/2c1d28d9119012019ed42f1a6798f5ce to your computer and use it in GitHub Desktop.
Use javascript to countdown to a specific date, produce a message, and reset to the following year after the date. Replace `<tag>`s.
// Replace:
// <event> for the event name, no spaces (FirstLetterCapitalized)
// <month> for month number (January is 0)
// <day> for day number
function updateCountdown() {
const now = new Date();
const currentYear = now.getFullYear();
// Check if today is <month>.<day>
if (now.getMonth() === <month> && now.getDate() === <day>) {
document.getElementById("countdown").textContent = `0 Days - It's <event>!`;
return;
}
// Define <month>.<day> of the current year
let eventDay = new Date(currentYear, <month>, <day>);
eventDay.setHours(0, 0, 0, 0); // Set to beginning of the day for consistent calculations
// If <month>.<day> has already passed this year, target next year's <month>.<day>
if (now > eventDay) {
eventDay = new Date(currentYear + 1, <month>, <day>);
eventDay.setHours(0, 0, 0, 0);
}
// Calculate the time difference
const timeDiff = eventDay - now;
// Convert time difference from milliseconds to days
const daysUntil<event> = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
// Update the DOM element
document.getElementById("countdown").textContent = `${daysUntil<event>} Days until next <event>`;
}
// Run the countdown function once
updateCountdown();
// Update the countdown every hour
setInterval(updateCountdown, 1000 * 60 * 60);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment