Javascript 在jquery中验证和排序日期
我正在使用table sorter插件对我的表进行排序。 我希望能够以以下格式捕获日期列: dd/MM/yyyy HH:MM 然后对它们进行正确排序(为此,我必须将日期与年份进行切换) 以下是我到目前为止所做的:Javascript 在jquery中验证和排序日期,javascript,jquery,regex,tablesorter,Javascript,Jquery,Regex,Tablesorter,我正在使用table sorter插件对我的表进行排序。 我希望能够以以下格式捕获日期列: 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}/.tes
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
,因此如果列中的第一个表单元格不匹配,它将忽略该解析器。因此,无论哪种方式,最好手动设置解析器
无论如何,下面是我将如何编写您正在描述的解析器():
至于解释正则表达式,上面的代码与您的问题没有太大区别。最大的区别在于,上述代码确保日期和时间之间只存在一个空格,并且日期可以用斜杠、破折号、句点、逗号或空格分隔(即1-1-2000
,1-2000
等)
更新:如果要自动检测此解析器,请使用以下
is
regex()。但需要注意的是,此正则表达式无法区分mmddyyyy和ddmmyyyy,因此它将始终检测ddmmyyy。要覆盖此选项,请将收割台分拣机选项设置为“shortDate”:
我为我的所有页面调用一次table sorter init,其中有许多表——因此我宁愿在is函数中实现逻辑,以允许使用正确格式的空字符串或日期。你能帮我用这个函数的正则表达式吗?非常感谢:)
$.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"
});
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, "/"));
},