Skip to content Skip to sidebar Skip to footer

Add Formats To Native Date Parser

I was wondering if there was any way to add (and map) formats to the native Date parser in javascript (without using a library). Similar to the defineParsers method that comes with

Solution 1:

I think your approach is probably the best. You essentially just want to add functionality to a native method. Although, this wouldn't touch the prototype as the parse method is static.

Here is a quick sample:

(function() {

    ​var nativeParse = Date.parse;
    var parsers = [];

    ​Date.parse = function(datestring) {
        for (var i = 0; i<parsers.length; i++) {
            var parser = parsers[i];
            if (parser.re.test(datestring)) {
                datestring = parser.handler.call(this, datestring);
                break;
            }
        }
        return nativeParse.call(this, datestring);
    }

    Date.defineParser = function(pattern, handler) {
        parsers.push({re:pattern, handler:handler});
    }

}());

Date.defineParser(/\d*\+\d*\+\d*/, function(datestring) {
    return datestring.replace(/\+/g, "/");
});

console.log(Date.parse("10+31+2012"));

Here it is on jsfiddle.

Post a Comment for "Add Formats To Native Date Parser"