问题
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