I'm in the process of building a website that requires a countdown to a specific time, but I'm struggling to find a solution that allows me to input a Unix timestamp and display the same countdown for all users, irrespective of their time zones.
I've come across various options involving jQuery and other libraries, but I'd prefer not to rely on any external libraries unless it's absolutely necessary.
Here's what I experimented with:
const countdownTimer = setInterval(() => {
const countDownTime = new Date("Mar 1 2024 11:00:00").getTime();
const currentTime = new Date().getTime();
const timeLeft = countDownTime - currentTime;
const daysLeft = Math.floor(timeLeft / (1000 * 60 * 60 * 24));
const hoursLeft = Math.floor((timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutesLeft = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
const secondsLeft = Math.floor((timeLeft % (1000 * 60)) / 1000);
if (timeLeft < 0) {
clearInterval(countdownTimer);
document.getElementsByClassName("countdown")[0].innerHTML = "Released!";
} else {
document.getElementsByClassName(
"countdown"
)[0].innerText = `${daysLeft}d ${hoursLeft}h ${minutesLeft}m ${secondsLeft}s`;
}
}, 1000);
Although everything is functioning as expected, the displayed time reflects my current timezone instead of the universal countdown I intended, since this timer indicates when the website will be launched.