javascriptunix-timestampcountdown

How do I make a JavaScript countdown using a Unix timestamp?


I am making a website that needs a countdown until a specific time, but I can't find anything that lets me input a Unix timestamp and gives the same countdown for all users, regardless of timezones.

I found some stuff using jQuery and other libraries, but I don't want to use any libraries unless I absolutely have to.

Here is what I tried:

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);

Everything works as expected, except the time is in my current timezone which is not what I want, because this is a countdown until a website I'm making releases.


Solution

  • This has been answered. All I had to do was change the time string to a timestamp and that seemed to fix it.

    const countDownTime = new Date(1709290800000).getTime();
    const currentTime = new Date().getTime();
    const timeLeft = countDownTime - currentTime;