Tuesday, September 6, 2011

[Javascript] date function return NaN in IE but work fine in Firefox

Sometimes, javascript run in IE and firefox have different interpretation on a string of date. If there is a date string, for example

2011-01-01T12:56:12

Well, I think it is a well-formatted date string and no-doubt that Javascript can change it to a date object without any mistake. However, I find that I got different return at IE and firefox. At IE, I got NaN, but I can get date object at firefox.

For a developer who have to meet tight deadline, we don't want to know what the back-end logic inside different browsers. Here is the function for you to cater this problem.


function parseISO8601(dateStringInRange) {

    var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)\s*$/,
        date = new Date(NaN), month,
        parts = isoExp.exec(dateStringInRange);
   
    if(parts) {
        month = +parts[2];
        date.setFullYear(parts[1], month - 1, parts[3], parts[4], parts[5], parts[6]);
        if(month != date.getMonth() + 1) {
            date.setTime(NaN);
        }
    }
    return date;

}

The input is YYYY-MM-DDTHH:ii:ss, output is date object and NaN if there is not a date input.
Related Posts Plugin for WordPress, Blogger...