My Technical Notes

Friday, 16 October 2015

Parsing UK Date using Javascript


function parseUkDate(str) {
    if (typeof str !== "string")
        return null; 

    var groups = (new RegExp("^(\\d{1,2})/(\\d{1,2})/(\\d{4})$")).exec(str);

    if (groups == null) {
        return null;
    } else {
        var days = parseInt(groups[1], 10);
        var months = parseInt(groups[2], 10) - 1;
        var years = parseInt(groups[3], 10);

        var dateObj = new Date(years, months, days);

        if (dateObj.getFullYear() !== years)
            return null;

        if (dateObj.getMonth() !== months)
            return null;

        if (dateObj.getDate() !== days)
            return null;

        return dateObj;
    }
}

No comments: