gpt4 book ai didi

javascript - 对字符串日期数组进行排序

转载 作者:数据小太阳 更新时间:2023-10-29 04:00:14 28 4
gpt4 key购买 nike

我想按升序对数组进行排序。日期是字符串格式

["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015", "18/05/2015"] 

甚至需要一个函数来检查这些日期是否是连续的:

eg - Valid   - ["09/06/2015", "10/06/2015", "11/06/2015"] 
Invalid - ["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015"]

示例代码:

function sequentialDates(dates){
var temp_date_array = [];

$.each(dates, function( index, date ) {
//var date_flag = Date.parse(date);
temp_date_array.push(date);
});

console.log(temp_date_array);

var last;
for (var i = 0, l = temp_date_array.length; i < l; i++) {

var cur = new Date();
cur.setTime(temp_date_array[i]);
last = last || cur;
//console.log(last+' '+cur);

if (isNewSequence(cur, last)) {
console.log("Not Sequence");
}
}

//return dates;
}

function isNewSequence(a, b) {
if (a - b > (24 * 60 * 60 * 1000))
return true;
return false;
}

最佳答案

简单的解决方案

无需将字符串转换为日期或使用 RegExp。

简单的解决方案是使用 Array.sort() 方法。排序函数将日期格式设置为 YYYYMMDD,然后比较字符串值。假设日期输入的格式为 DD/MM/YYYY。

data.sort(function(a,b) {
a = a.split('/').reverse().join('');
b = b.split('/').reverse().join('');
return a > b ? 1 : a < b ? -1 : 0;
// return a.localeCompare(b); // <-- alternative
});

更新:

一条有用的评论建议使用 localeCompare() 来简化排序功能。上面的代码片段中显示了这种替代方法。

运行代码段进行测试

<!doctype html>
<html>
<body style="font-family: monospace">
<ol id="stdout"></ol>
<script>
var data = ["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015", "18/05/2015"];

data.sort(function(a,b) {
a = a.split('/').reverse().join('');
b = b.split('/').reverse().join('');
return a > b ? 1 : a < b ? -1 : 0;

// return a.localeCompare(b); // <-- alternative

});

for(var i=0; i<data.length; i++)
stdout.innerHTML += '<li>' + data[i];
</script>
</body>
</html>

关于javascript - 对字符串日期数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30691066/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com