Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

jquery - Safari Javascript Date() NaN Issue (yyyy-MM-dd HH:mm:ss)

My code is working properly in Google Chrome, but not in Safari.

I figured out that I need to convert yyyy-MM-dd HH:mm:ss to ISO 8601, but I didn't found a solution to do this.


Online Test Link: http://jsfiddle.net/UVgHR/


Javascript:

$(document).ready(function() {

    calculateMinutes();
    setInterval(calculateMinutes, 60000);

});

function calculateMinutes() {
    $('.calculateMinutes').each(function () {
        var diff = Math.abs(new Date( $(this).data('timestamp') ) - new Date());
        var minutes = Math.floor((diff/1000)/60);
        $(this).html( minutes + ' min.' );
    });
}

HTML Example:

<span class="calculateMinutes" data-timestamp="2014-02-18 15:00:48">
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To make your question easier your problem is with:

new Date('2014-02-18 15:00:48')

This work okay in chrome but not in safari. The mdn talks about ECMAScript 5 ISO-8601 format support says:

Alternatively, the date/time string may be in ISO 8601 format. For example, "2011-10-10" (just date) or "2011-10-10T14:48:00" (date and time) can be passed and parsed.

If you include T it works:

new Date('2014-02-18T15:00:48')

You can use new Date('2014-02-18T15:00:48'.replace(/s/, 'T')).

If you handle a lot of cases like this I will recommend using moment which seems to handle this case very well with or without T: parsing from string. Additionally your whole example is easier with momentjs:

var minutes = moment().diff("2014-02-18 15:00:48", 'minutes');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...