如何比较数组中的日期以找到最早的日期? [英] how can I compare dates in array to find the earliest one?
本文介绍了如何比较数组中的日期以找到最早的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为dateArray的变量,其日期为
,例如
I have a variable called dateArray with dates in it for example
["09/09/2009", "16/07/2010", "29/01/2001"]
我想要找到最早的一个带有for循环,结果将是
and I want to find the earliest one with a for loop so the result will be
"29/01/2001" - or dateArray[2]
语言是javascript
the language is javascript
推荐答案
有时最基本的方法是最好的:
Sometimes the most basic approach is the best:
var dates = ["09/09/2009", "16/07/2010", "29/01/2001"];
var min = dates[0];
for(var i = 1; i < dates.length; i++) {
if (fDate(dates[i]) < fDate(min))
min = dates[i];
}
alert(min);
// create a proper Date object from the string
function fDate(s) {
var d = new Date();
s = s.split('/');
d.setFullYear(s[2]);
d.setMonth(s[1]);
d.setDate(s[0]);
return d;
}
我上面为你写的代码转换每个将字符串转换为Date对象,然后从它们中找到最小值(最早的日期)。没有字符串黑客,只是简单的日期比较。它返回数组中的原始字符串。
The code I wrote for you above converts each string into a Date object, and then finds the minimum (the earliest date) from them. No string hacks, just straightforward date comparison. It returns the original string from the array.
这篇关于如何比较数组中的日期以找到最早的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文