将格式添加到本机日期解析器 [英] Add formats to native Date parser

查看:92
本文介绍了将格式添加到本机日期解析器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有任何方法可以向javascript中的本机Date解析器中添加(和映射)格式(不使用库)。

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

类似于Mootools扩展Date对象附带的 defineParsers 方法(如果您熟悉的话),但没有Mootools。

Similar to the defineParsers method that comes with the Mootools extended Date object, if you are familiar with it, but without Mootools.

我能想到的最简单的解决方案是,将Date原型解析方法替换为将原始日期包装并首先将输入日期重新排列为有效格式的方法,就像这样:

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);

有没有更简单的方法? javascript是否使用任何可访问的数据结构来存储与日期格式及其相应映射有关的信息?

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?

推荐答案

我认为您的方法是可能是最好的。本质上,您只想向本机方法添加功能。虽然,这不会触及原型,因为parse方法是静态的。

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.

这里是一个快速示例:

(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"));

此处位于 jsfiddle

这篇关于将格式添加到本机日期解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆