我正在制作一个需要倒计时直到特定时间的网站,但我找不到任何可以让我输入 Unix 时间戳并为所有用户提供相同倒计时的东西,无论时区如何。
我发现了一些使用 jQuery 和其他库的东西,但我不想使用任何库,除非绝对必要。
这是我尝试过的:
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);
一切都按预期进行,除了时间是在我当前的时区,这不是我想要的,因为这是我正在发布的网站的倒计时。
这个问题已经得到解答。我所要做的就是将时间字符串更改为时间戳,这似乎解决了问题。
const countDownTime = new Date(1709290800000).getTime();
const currentTime = new Date().getTime();
const timeLeft = countDownTime - currentTime;