Moment.js - 具有多个实例/时区感知倒数计时器的不正确时区

时间:2018-04-17 16:34:43

标签: javascript jquery momentjs countdown countdowntimer

我正在使用jQuery.countdown和moment.js创建一个多实例/时区感知倒数计时器。除时区外,一切都有效。投掷时区会将倒计时更改为GMT,而不是我指定的区域。无论我选择什么时区,计时器都保持格林威治标准时间。

我正在使用最新版本的moment.js和moment-timezone-with-data-2012-2022.js。我花了太多时间试图解决这个问题,请帮忙!

$(function(){
    $('[data-countdown]').each(function() {
        var $this = $(this), finalDate = $(this).data('countdown');
        var finalDate = moment.tz(finalDate, 'America/Los_Angeles');
        $this.countdown(finalDate.toDate(), function(event) {
            var totalHours = event.offset.totalDays * 24 + event.offset.hours;
            $(this).html(event.strftime('Expires in ' + totalHours + ' hr %-M min'));
        });
    });
});
  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.countdown/2.2.0/jquery.countdown.min.js"></script>
  <script src="https://cdn.jsdelivr.net/momentjs/2.14.1/moment-with-locales.min.js"></script>
  <script src="https://momentjs.com/downloads/moment-timezone-with-data.js"></script>

  <div data-countdown="04/18/2018 00:00:00"></div>
  <div data-countdown="04/19/2018 00:00:00"></div>
  <div data-countdown="04/20/2018 00:00:00"></div>

1 个答案:

答案 0 :(得分:1)

您的问题似乎来自控制台中显示的此警告:

  

弃用警告:时刻构建回落到日期。这是不鼓励的,将在即将发布的主要版本中删除。有关详细信息,请参阅http://momentjs.com/guides/#/warnings/js-date/

这是由您传递的非标准日期格式引起的,而不会告诉传入的格式。要修复,只需指定传入格式。如下所述:Parsing in Zone并显示在下面的代码中。

$(function(){
    $('[data-countdown]').each(function() {
        var $this = $(this), 
            countdown = $(this).data('countdown');

        // set the incoming date format as the 2nd paramater to the constructor
        var finalDate = moment.tz(countdown, 'MM/DD/YYYY HH:mm:ss', 'America/Los_Angeles');
        
        $this.countdown(finalDate.toDate(), function(event) {
            var totalHours = event.offset.totalDays * 24 + event.offset.hours;
            $(this).html(event.strftime('Expires in ' + totalHours + ' hr %-M min'));
        });
    });
});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.countdown/2.2.0/jquery.countdown.min.js"></script>
<script src="https://cdn.jsdelivr.net/momentjs/2.14.1/moment-with-locales.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.js"></script>

<div data-countdown="04/18/2018 00:00:00"></div>
<div data-countdown="04/19/2018 00:00:00"></div>
<div data-countdown="04/20/2018 00:00:00"></div>