My Technical Notes

Tuesday, 19 March 2013

Parsing a Date String in JavaScript UK Format

The following is my code to parse a string into a date, when the date string is in UK format, that is, dd/MM/yyyy:


//#region dateObj - a utility object for parsing dates
dateObj = {};

dateObj.parseDate = function (str) {

    // new Date(year, month - 1, day) <- how to turn three integers into a date object
    var dateExp = new RegExp(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/)

    if (str === null || $.trim(str) === '' || dateExp.test(str) === false) {
        return null;
    } else {
        var components = dateExp.exec(str);
        var day = parseInt(components[1]);
        var month = parseInt(components[2]);
        var year = parseInt(components[3]);

        var candidateDate = new Date(year, month - 1, day);

        if (candidateDate.getFullYear() !== year) return null;
        if (candidateDate.getMonth() !== (month -1)) return null;
        if (candidateDate.getDate() !== day) return null;

        return candidateDate;
    }
};

//#endregion dateObj

The dateObj.parseDate function will return null if the date string is not in the right format, otherwise it will return the parsed Date object. We can use it as follows:


dateObj.ParseDate('19/03/2013');  // date
dateObj.ParseDate('19/3/2013');   // date
dateObj.ParseDate('3/19/2013');   // null
dateObj.ParseDate('hello world'); // null

No comments: