使用Moment js的倒数计时器 [英] Countdown timer using Moment js

查看:121
本文介绍了使用Moment js的倒数计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个事件页面制作一个倒数计时器,我用了这个时刻js。

I am making a countdown timer for an event page, i used moment js for this.

这是小提琴

我正在计算事件日期和当前日期(时间戳)之间的日期差异,然后从时刻js使用持续时间方法。但剩下的时间并未达到预期。

预计 - 00:30m:00s

实际 - 5h:59m :00s

I am calculating date difference between event date and current date (timestamp), then using "duration" method from moment js. But the time left is not coming as expected.
Expected - 00:30m:00s
Actual - 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文档以找出问题,但没有运气。

I read the momentjs documentation to figure out the problem, but no luck.

感谢您的时间。

更新:

我最终这样做:

<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>

JS Fiddle

推荐答案

在最后一个语句中,您将持续时间转换为也考虑时区的时间。我假设你的时区是+530,所以5小时30分钟就会增加到30分钟。你可以这样做。

In the last statement you are converting the duration to time which also considers the timezone. I assume that your timezone is +530, so 5 hours and 30 minutes gets added to 30 minutes. You can do as given below.

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);

这篇关于使用Moment js的倒数计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆