简体   繁体   中英

Parse date function not working on some dates

Hoping you can help me out, I'm trying to work out why this parse date function that I wrote is not working for the 29th May 2014 (and possibly other dates)

function parseDate(dateString){
    //Accepts DD/MM/YYYY HH:MM
    var date = new Date(); 
    date.setDate    (parseInt(dateString.substr(0, 2), 10));
    date.setMonth   (parseInt(dateString.substr(3, 2), 10) - 1);
    date.setYear    (parseInt(dateString.substr(6, 4), 10));
    date.setHours   (parseInt(dateString.substr(11, 2), 10));
    date.setMinutes (0);
    date.setSeconds (0);
    date.setMilliseconds (0);
    return date;
}


$('#result').text(parseDate('29/05/2014 08:00'));
//Result Thu May 01 2014 08:00:00 GMT+1000 (EST)

A link to the fiddle is here: http://jsfiddle.net/2k4Ux/

Its probably something stupid but I just can't figure it out at the moment.

You should change the order of your operations, like this: http://jsfiddle.net/maximgladkov/m6sUM/1/

function parseDate(dateString){
    //Accepts DD/MM/YYYY HH:MM
    var date = new Date(); 
    date.setYear    (parseInt(dateString.substr(6, 4), 10));
    date.setMonth   (parseInt(dateString.substr(3, 2), 10) - 1);
    date.setDate    (parseInt(dateString.substr(0, 2), 10));
    date.setHours   (parseInt(dateString.substr(11, 2), 10));
    date.setMinutes (0);
    date.setSeconds (0);
    date.setMilliseconds (0);

    return date;
}

$('#result').text(parseDate('29/05/2014 08:00'));

Not all months have more than 28 days, so before you set year and month, Date object cannot determine, if the date is valid.

You could do this :

function parseDate(dateString) {
    var parts = dateString.match(/\d+/g);
    return new Date(
        parts[2], parts[1] - 1, parts[0], // date
        parts[3], parts[4] // time
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM