我有这个代码,但唯一的问题是我无法弄清楚如何为它添加时区。我有日期设定但没有时区。我如何将它添加到countDownDate?
// Set the date we're counting down to
var countDownDate = new Date("May 8, 2018 16:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
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);
document.getElementById("countdown").innerHTML = "<p>" + hours + ":" + minutes + ":" + seconds + "</p>";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("countdown").innerHTML = "expired";
}
}, 1000);
<div id="countdown"></div>
答案 0 :(得分:0)
新的Date()对象位于系统的本地时区。如果要直接设置时区,一种方法是以UTC时间创建时间,然后添加您要查找的本地时区的偏移量。
let dateUTC = new Date(Date.UTC('...'))
let offset = (60*60*1000) * 4 // EST would be UTC+4, hence 4 * the number of ms in an hour.
let dateEST = dateUTC+offset
另一种方法是使用日期字符串,并指定时区:
let dateEST = new Date('2018-05-08T14:45:00+0400') //The '+0400' is the '+4' for EST.
答案 1 :(得分:0)
编辑:只是尝试将“GMT”添加到我的日期变量中并且它可以正常工作。没想到那会。
所以我现在有:
var countDownDate = new Date("May 8, 2018 16:00:00 GMT").getTime();
我从时区设定时间+/-并且有效。