如何将受本地时区影响的JavaScript倒计时改为通用时区倒计时?
解决倒计时受本地时区影响的问题
你的问题根源在于创建目标日期时,new Date("July 26, 2022 19:00:00")会按照用户的本地时区解析时间,导致不同时区用户看到的结束时间不一致。要实现通用UTC时区倒计时,只需确保目标日期被解析为UTC时间即可,以下是两种简便修复方法:
方法1:在日期字符串后添加UTC标识
直接在时间字符串末尾追加UTC,让浏览器将其解析为UTC标准时间:
// Set the date we're counting down to (UTC时间) var countDownDate = new Date("July 26, 2022 19:00:00 UTC").getTime(); // Update the count down every 1 second var countdownfunction = setInterval(function() { // Get todays date and time(getTime()返回UTC时间戳,不受时区影响) var now = new Date().getTime(); // Find the distance between now an the count down date var distance = countDownDate - now; // Time calculations for days, hours, minutes and seconds var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); // Output the result in an element with id="countdown" document.getElementById("countdown").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s "; // If the count down is over, write some text if (distance < 0) { clearInterval(countdownfunction); document.getElementById("countdown").innerHTML = "Refresh the page! Ctrl+F5"; } }, 1000);
方法2:使用Date.UTC()创建UTC时间戳
Date.UTC()直接返回指定UTC时间的时间戳,注意月份参数是0索引的(1月对应0,7月对应6):
// Set the date we're counting down to (UTC时间,6代表7月) var countDownDate = Date.UTC(2022, 6, 26, 19, 0, 0); // 后续代码保持不变...
两种方法都能让所有用户的倒计时指向同一个UTC时间,彻底解决时区差异问题。
内容的提问来源于stack exchange,提问作者Do you even lift BRAH
相关产品推荐
相关产品推荐

