如何更改Javascript中的日期格式以启用排序? [英] How do I change date formatting in Javascript to enable sorting?
本文介绍了如何更改Javascript中的日期格式以启用排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我通过以下方式写生日:
I am writing my dates of birth in the following manner:
- 4.02.1976 14:37
- 1.7.1990 11:35
- 10.10.1910 18:00
我想使用类似于以下代码的方式对其进行排序(启用按天生的排序):
I wanted to sort it using something similar to this code (enabling sorting by birth):
var obj = [{"id":1,"dateOfBirth":"1.7.1990 11:35"},
{"id":4,"dateOfBirth":"4.02.1976 14:37"},{"id":2,"dateOfBirth":"28.10.1950
2:15"},{"id":3,"dateOfBirth":"03.01.1963 23:10"}]
obj.sort(function(a,b) { return new Date(a.dateOfBirth).getTime() - new
Date(b.dateOfBirth).getTime() } );
我不确定是否需要重新设定出生日期才能实现这一目标.
I am unsure if I need to reformat the dates of birth to achieve this.
推荐答案
具有可选时间值的有效版本.
A working version with optional time values.
var obj = [{
"id": 1,
"dateOfBirth": "1.7.1990"
},
{
"id": 4,
"dateOfBirth": "4.02.1976 14:37"
}, {
"id": 2,
"dateOfBirth": "28.10.1950 2:15"
}
];
console.log(
obj.sort(function(a, b) {
return parseDate(a.dateOfBirth) -
parseDate(b.dateOfBirth);
})
);
function parseDate(str) {
var tokens = str.split(/\D/);
while (tokens.length < 5)
tokens.push(0);
return new Date(tokens[2], tokens[1]-1, tokens[0], tokens[3]||0, tokens[4]||0);
}
这篇关于如何更改Javascript中的日期格式以启用排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文