Add formats to native Date parser

穿精又带淫゛_ 提交于 2019-12-24 10:27:09

问题


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 the Mootools extended Date object, if you are familiar with it, but without Mootools.

The simplest solution I can think of would be to simply replace the Date prototype parse method with one that wraps the original and rearranges input dates to a valid format first, like this:

Date.prototype.parse = (function(oldVersion) {
    function extendedParse(dateString) {
        //change dateString to an acceptable format here
        oldVersion(dateString);
    }
    return extendedParse;
})(Date.prototype.parse);

But is there an easier way? Are there any accessible data structures javascript uses to store information pertaining to date formats and their appropriate mappings?


回答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.



来源:https://stackoverflow.com/questions/13162113/add-formats-to-native-date-parser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!