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

前端 未结 3 1724
一生所求
一生所求 2020-11-27 19:25

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

相关标签:
3条回答
  • 2020-11-27 20:11

    I think Jose missed one point here - Do not forget to include Z or else there will be lag of the timezone.

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

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

    Refer this for more info - new Date() works differently in Chrome and Firefox

    0 讨论(0)
  • 2020-11-27 20:15

    I've seen an issue like this before and what works for me is to replace the space between the Date and the Time with a T. Try this:

    Updated JavaScript:

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

    JSFiddle here.

    0 讨论(0)
  • 2020-11-27 20:17

    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');
    
    0 讨论(0)
提交回复
热议问题