我正在为一个事件页面制作一个倒数计时器,我为此使用了 moment js。
这里是 fiddle为此。
我正在计算事件日期和当前日期(时间戳)之间的日期差异,然后使用时刻 js 的“持续时间”方法。但是剩下的时间并没有如期而至。
预期 - 00:30m:00s
实际 - 5h:59m:00s
代码:
<script>
$(document).ready(function(){
var eventTime = '1366549200';
var currentTime = '1366547400';
var time = eventTime - currentTime;
var duration = moment.duration(time*1000, 'milliseconds');
var interval = 1000;
setInterval(function(){
duration = moment.duration(duration.asMilliseconds() - interval, 'milliseconds');
$('.countdown').text(moment(duration.asMilliseconds()).format('H[h]:mm[m]:ss[s]'));
}, interval);
});
</script>
我阅读了 momentjs 文档以找出问题所在,但没有成功。
感谢您的宝贵时间。
更新:
我最终会这样做:
<script>
$(document).ready(function(){
var eventTime = '1366549200';
var currentTime = '1366547400';
var leftTime = eventTime - currentTime;//Now i am passing the left time from controller itself which handles timezone stuff (UTC), just to simply question i used harcoded values.
var duration = moment.duration(leftTime, 'seconds');
var interval = 1000;
setInterval(function(){
// Time Out check
if (duration.asSeconds() <= 0) {
clearInterval(intervalId);
window.location.reload(true); #skip the cache and reload the page from the server
}
//Otherwise
duration = moment.duration(duration.asSeconds() - 1, 'seconds');
$('.countdown').text(duration.days() + 'd:' + duration.hours()+ 'h:' + duration.minutes()+ 'm:' + duration.seconds() + 's');
}, interval);
});
</script>
最佳答案
在最后一条语句中,您将持续时间转换为同时考虑时区的时间。我假设您的时区是 +530,因此 5 小时 30 分钟加到 30 分钟。您可以按照下面的说明进行操作。
var eventTime= 1366549200; // Timestamp - Sun, 21 Apr 2013 13:00:00 GMT
var currentTime = 1366547400; // Timestamp - Sun, 21 Apr 2013 12:30:00 GMT
var diffTime = eventTime - currentTime;
var duration = moment.duration(diffTime*1000, 'milliseconds');
var interval = 1000;
setInterval(function(){
duration = moment.duration(duration - interval, 'milliseconds');
$('.countdown').text(duration.hours() + ":" + duration.minutes() + ":" + duration.seconds())
}, interval);
关于javascript - 使用Moment js的倒数计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16129157/