我在2个日期之间显示计数器时遇到问题。我知道这个问题,时区是GMT+05:30
我需要知道,如何纠正
我的解决方案:
var start = new Date();
var end = new Date("2017-10-03"); // This date is coming from database as <?php echo $date_end; ?>
function getClock() {
var start = new Date();
var end = new Date("<?php echo $date_end; ?>");
var diff = Math.round((end.getTime() - start.getTime()) / 1000);
var hours = Math.floor(diff / 3600);
diff -= hours * 3600
var minutes = Math.floor(diff / 60);
diff -= minutes * 60;
var seconds = diff % 60;
if(document.getElementById('countdown')){
document.getElementById('countdown').innerHTML = "<span>"
+ hours + "</span> hours <span>" + minutes + "</span> minutes <span>"
+ seconds + "</span> seconds";
}
}
setInterval('getClock()', 1000);
由于开始日期为02 Oct 10PM
,结束日期为03 Oct
。因此,按时间计算,我将获得 2 hours
但是我得到的计时器是2小时+ 5:30 = 7:30小时。
请帮助获得正确的计时器。
JS小提琴链接是HERE
答案 0 :(得分:1)
答案 1 :(得分:1)
尝试这样的事情。
setInterval(function(){
var start = new Date();
var end = new Date("2017-10-03 00:00:00");
var diff = Math.round((end.getTime() - start.getTime()) / 1000);
var hours = Math.floor(diff / 3600);
diff -= hours * 3600
var minutes = Math.floor(diff / 60);
diff -= minutes * 60;
var seconds = diff % 60;
if(document.getElementById('countdown')){
document.getElementById('countdown').innerHTML = "<span>"
+ hours + "</span> hours <span>" + minutes + "</span> minutes <span>"
+ seconds + "</span> seconds";
}
}, 1000);
答案 2 :(得分:0)
问题是由于Javascript在Date构造函数中处理时区的方式(请查看文档以获取详细信息)。如果你通过(2017年,9月3日),而不是通过(“2017-10-03”),它应该工作。为了避免这些问题,最好始终使用UTC。
答案 3 :(得分:0)
确保您分别通过年,月和日来初始化日期,因此使用系统时区,与初始化start
日期时相同:
var end_str = "<?php echo $date_end; ?>";
var arr = end_str.split("-")
arr = Date.new(arr[0], arr[1]-1, arr[2]); //month is 0-indexed