【发布时间】:2013-04-14 07:05:09
【问题描述】:
我正在为活动页面制作倒计时,我为此使用了 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>
【问题讨论】:
-
什么是“预期”?我们无法读懂您的想法以了解您的实际期望。
-
@zerkms - 我相信相差30分钟,从1小时30分开始倒计时
-
@zerkms - 更新问题。
-
momentjs 不格式化时间跨度,而是格式化日期。如果您输出日期(除了时间),您会看到它是 unix 纪元的第一天,您的时区偏移
-
github.com/icambron/moment-countdown moment-countdown 是一个与 Countdown.js 集成的小 moment.js 插件
标签: javascript jquery countdown unix-timestamp momentjs