在jquery中验证和排序日期

validate and sort date in jquery

本文关键字:排序 日期 验证 jquery      更新时间:2023-09-26

我正在使用表分类器插件对表进行排序。我希望能够捕捉格式为的日期列

dd/MM/yyyy HH:MM

然后对它们进行正确的排序(为此,我必须将日期与年份进行切换)。

以下是我迄今为止所做的:

ts.addParser({
        id: "hebreLongDate",
        is: function (s) {
            return /'d{1,2}['/'-]'d{1,2}['/'-]'d{2,4} d{1,2}:d{1,2}/.test(s);
        }, format: function (s, table) {
            var c = table.config;
            s = s.replace(/'-/g, "/");
            // reformat the string in ISO format
            s = s.replace(/('d{1,2})['/'-]('d{1,2})['/'-]('d{4})/, "$3/$2/$1");
            return $.tablesorter.formatFloat(new Date(s).getTime());
        }, type: "numeric"
    });

它不起作用。

如果有任何帮助,我将不胜感激,尤其是如果它能解释正确正则表达式的含义。

谢谢,Omer

解析器并没有真正验证日期。is函数只检测格式是否与format函数的模式匹配,这就是为什么更容易使其返回false,并使用headers选项手动设置列的解析器:

headers: {
    1: { sorter: "hebreLongDate" }
},

上面的is函数需要模式中的HH:mm,因此如果列中的第一个表单元格不匹配,它将忽略该解析器。因此,无论哪种方式,手动设置解析器都会更好。

无论如何,以下是我将如何编写您正在描述的解析器(演示):

$.tablesorter.addParser({
    id: "hebreLongDate",
    is: function(s) {
        return false;
    },
    format: function(s, table, cell, cellIndex) {
        s = s
            // replace separators
            .replace(/'s+/g," ").replace(/['-.,]/g, "/")
            // reformat dd/mm/yyyy to yyyy/mm/dd
            .replace(/('d{1,2})['/'s]('d{1,2})['/'s]('d{4})/, "$3/$2/$1");
       return s ? $.tablesorter.formatFloat( (new Date(s).getTime() || ''), table) : s;
    },
    type: "numeric"
});

至于解释正则表达式,上面的代码和您的问题中的代码没有太大区别。最大的区别在于,上面的代码确保日期和时间之间只有一个空格,并且日期可以用斜线、破折号、句点、逗号或空格(即1-1-20001 1 2000等)分隔。


更新:如果你想让这个解析器被自动检测,那么使用下面的is正则表达式(更新的演示)。但需要注意的是,此regex无法区分mmddyyyy和ddmmyyyy,因此它将始终检测ddmmyyyy。要覆盖此项,请将表头分拣机选项设置为"shortDate":

is: function(s) {
    // testing for ##-##-####, so it's not perfect; time is optional
    return (/(^'d{1,2}['/'s]'d{1,2}['/'s]'d{4})/).test((s || '').replace(/'s+/g," ").replace(/['-.,]/g, "/"));
},