使用 Moment js 的倒数计时器

IT技术 javascript jquery countdown unix-timestamp momentjs
2021-02-24 22:07:50

我正在为事件页面制作倒数计时器,为此我使用了 moment js。

这是小提琴

我正在计算事件日期和当前日期(时间戳)之间的日期差异,然后使用 moment 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>

JS小提琴

6个回答

在最后一条语句中,您将持续时间转换为也考虑时区的时间。我假设您的时区是 +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);
非常感谢您指出这一点!让我更正一下,diffTime以秒为单位,因为根据问题中给出的日期,“1366549200”和“1366547400”以秒为单位。
2021-04-23 22:07:50
diffTime 已经以毫秒为单位了,为什么在设置持续时间时要乘以 1000?
2021-05-04 22:07:50
new Date('Sun, 21 Apr 2013 13:00:00 GMT').getTime(); // = 1366549200000 in milliseconds
2021-05-08 22:07:50
如果有人发现了上述评论困惑(像我一样),你通过1000作为.getTime自1970/01/01返回的毫秒数需乘diffTime。
2021-05-08 22:07:50
不,它以秒为单位,因为 '1366549200000' 和 '1366547400' 以秒为单位。
2021-05-20 22:07:50

看看这个插件:

瞬间倒计时

moment-countdown 是一个Countdown.js集成的小moment.js插件 文件在这里

怎么运行的?

//from then until now
moment("1982-5-25").countdown().toString(); //=> '30 years, 10 months, 14 days, 1 hour, 8 minutes, and 14 seconds'

//accepts a moment, JS Date, or anything parsable by the Date constructor
moment("1955-8-21").countdown("1982-5-25").toString(); //=> '26 years, 9 months, and 4 days'

//also works with the args flipped, like diff()
moment("1982-5-25").countdown("1955-8-21").toString(); //=> '26 years, 9 months, and 4 days'

//accepts all of countdown's options
moment().countdown("1982-5-25", countdown.MONTHS|countdown.WEEKS, NaN, 2).toString(); //=> '370 months, and 2.01 weeks'
2021-05-08 22:07:50
这是工作!但我不能将它用作moment(date).lang('ru').countdown():( 请帮帮我
2021-05-17 22:07:50

虽然我确信这不会被接受作为这个非常古老问题的答案,但我来到这里是为了寻找一种方法来解决这个问题,这就是我解决问题的方法。

在 codepen.io 上创建了一个演示

Html:

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js" type="text/javascript"></script>
<script src="https://cdn.rawgit.com/mckamey/countdownjs/master/countdown.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/jquery-3.0.0.min.js" type="text/javascript"></script>
<div>
  The time is now: <span class="now"></span>, a timer will go off <span class="duration"></span> at <span class="then"></span>
</div>
<div class="difference">The timer is set to go off <span></span></div>
<div class="countdown"></div>

Javascript:

var now = moment(); // new Date().getTime();
var then = moment().add(60, 'seconds'); // new Date(now + 60 * 1000);

$(".now").text(moment(now).format('h:mm:ss a'));
$(".then").text(moment(then).format('h:mm:ss a'));
$(".duration").text(moment(now).to(then));
(function timerLoop() {
  $(".difference > span").text(moment().to(then));
  $(".countdown").text(countdown(then).toString());
  requestAnimationFrame(timerLoop);
})();

输出:

The time is now: 5:29:35 pm, a timer will go off in a minute at 5:30:35 pm
The timer is set to go off in a minute
1 minute

注意:上面的第 2 行按照momentjs更新,上面的第 3 行按照countdownjs更新,所有这些都以大约 60FPS 的速度进行动画处理,因为requestAnimationFrame()


代码片段:

或者,您可以查看此代码片段:

var now = moment(); // new Date().getTime();
var then = moment().add(60, 'seconds'); // new Date(now + 60 * 1000);

$(".now").text(moment(now).format('h:mm:ss a'));
$(".then").text(moment(then).format('h:mm:ss a'));
$(".duration").text(moment(now).to(then));
(function timerLoop() {
  $(".difference > span").text(moment().to(then));
  $(".countdown").text(countdown(then).toString());
  requestAnimationFrame(timerLoop);
})();

// CountdownJS: http://countdownjs.org/
// Rawgit: http://rawgit.com/
// MomentJS: http://momentjs.com/
// jQuery: https://jquery.com/
// Light reading about the requestAnimationFrame pattern:
// http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
// https://css-tricks.com/using-requestanimationframe/
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js" type="text/javascript"></script>
<script src="https://cdn.rawgit.com/mckamey/countdownjs/master/countdown.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/jquery-3.0.0.min.js" type="text/javascript"></script>
<div>
  The time is now: <span class="now"></span>,
</div>
<div>
  a timer will go off <span class="duration"></span> at <span class="then"></span>
</div>
<div class="difference">The timer is set to go off <span></span></div>
<div class="countdown"></div>

要求:

可选要求:

此外,这里有一些关于该requestAnimationFrame()模式的轻松阅读

我发现requestAnimationFrame()模式是比setInterval()模式更优雅的解决方案

我想我也会把它扔在那里(没有插件)。它倒计时 10 秒到未来。

    var countDownDate = moment().add(10, 'seconds');

      var x = setInterval(function() {
        diff = countDownDate.diff(moment());
    
        if (diff <= 0) {
          clearInterval(x);
           // If the count down is finished, write some text 
          $('.countdown').text("EXPIRED");
        } else
          $('.countdown').text(moment.utc(diff).format("HH:mm:ss"));

      }, 1000);
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="countdown"></div>

此解决方案仅适用于总持续时间少于 24 小时的情况,如果超过 24 小时,请遵循此方法 -> stackoverflow.com/a/18624295/5052778
2021-04-26 22:07:50

时区。getTimezoneOffset()如果您希望来自世界各地的访问者获得相同的时间则必须通过使用来处理它们

试试这个http://jsfiddle.net/cxyms/2/,它对我有用,但我不确定它是否适用于其他时区。

var eventTimeStamp = '1366549200'; // Timestamp - Sun, 21 Apr 2013 13:00:00 GMT
var currentTimeStamp = '1366547400'; // Timestamp - Sun, 21 Apr 2013 12:30:00 GMT

var eventTime = new Date();
eventTime.setTime(366549200);

var Offset = new Date(eventTime.getTimezoneOffset()*60000)

var Diff = eventTimeStamp - currentTimeStamp + (Offset.getTime() / 2);
var duration = moment.duration(Diff, '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);