2

I am creating a penny auction site and I have several auctions on the home page. Each auction gets its own timer based on a date from the mysql date format, which is in format 'Y-m-d H:i:s'.

The code works fine and the timers all start counting down perfectly on Firefox and Chrome, but in Safari the number shows NaN:NaN:NaN

Here's my function, its using the jquery countdown plugin by Keith Wood:

function updateTimers() {
        $( ".il-timer" ).each(function( index ) {

            var timer = $(this);
           var end_date = $(timer).attr('data-end-date');
           var auction_id = $(timer).attr('data-auction-id');

           var end = new Date(Date.parse(end_date,"yyyy-mm-dd hh:mm:ss"));

          $('#auction_listing_timer_'+auction_id).countdown({until: end, format: 'HMS', compact: true, description: ''});

          //Do it every 10 seconds...
            setTimeout(function(){

                updateTimers();

            }, 10000);

        });
    };
4

1 回答 1

9

一些东西:

  • Date.parse函数不采用第二个参数。"yyyy-mm-dd hh:mm:ss"您传递的值被忽略。

  • JavaScript 中的日期解析依赖于实现。Firefox 选择不解析该特定格式的值。

  • new Date(Date.parse(...))是多余的。您可以将字符串传递给日期构造函数。

  • 一个快速的解决方法是在解析之前用斜杠替换破折号:

    var end = new Date(end_date.replace(/-/g, '/'));
    
  • 更好的方法是使用像moment.js这样的库,这样您就可以控制用于解析的格式:

    var end = moment(end_date, 'YYYY-MM-DD HH:mm:ss').toDate();
    
于 2014-08-04T04:32:13.893 回答