Date.parse failing in IE 11 with NaN

后端 未结 1 853
深忆病人
深忆病人 2021-01-18 06:52

When i try to parse a date in IE 11, its throwing me NaN, but in chrome/firefox i get the below timestamp 1494559800000

Date.parse(         


        
1条回答
  •  北恋
    北恋 (楼主)
    2021-01-18 07:53

    According to MDN docs for Date.parse() parameter:

    dateString

    A string representing an RFC2822 or ISO 8601 date (other formats may be used, but results may be unexpected).

    Looks like Microsoft simply didn't implement the format you provided. I wouldn't use this format anyway, because it's locale dependent(might just be dd/mm/yyyy or sometimes might also fit mm/dd/yyyy).

    An alternative to your solution is to use moment.js. It has a very powerful API for creating/parsing/manipulating dates. I'll show some examples on how you could use it:

    //Create an instance with the current date and time
    var now = moment();
    
    //Parse the first the first argument using the format specified in the second
    var specificTime = moment('5‎/‎12‎/‎2017 09:00 AM', 'DD/MM/YYYY hh:mm a');
    
    //Compares the current date with the one specified
    var beforeNow = specificTime.isBefore(now);
    

    It offers a lot more and might help you simplify your code a great deal.

    Edit: I rewrote your code using moment.js version 2.18.1 and it looks like this:

    function parseDateCustom(date) {
        return moment(date, 'YYYY-MM-DD hh:mm a');
    }
    
    var tArray = ["09:00 AM", "05:00 PM"];
    var currentDate = moment().format('YYYY-MM-DD') + ' ';
    var timeString1 = parseDateCustom(currentDate + tArray[0]);
    var timeString2 = parseDateCustom(currentDate + tArray[1]);
    var currentTimeString = parseDateCustom(currentDate + "01:18 pm");
    
    if (timeString1.isBefore(currentTimeString) && currentTimeString.isBefore(timeString2)) {
        console.log('Sucess');
    } else {
        console.log('Failed');
    }
    

    0 讨论(0)
提交回复
热议问题