如何使用 JavaScript 在数组中找到最早的日期

How to find the earliest date in an array using JavaScript

如何使用 JavaScript 在数组中找到最早日期,即最小日期?

示例:

1
["10-Jan-2013","12-Dec-2013","1-Sep-2013","15-Sep-2013"]

我的输出应该是:

1
["10-Jan-2013","1-Sep-2013","15-Sep-2013","12-Dec-2013"]

我该怎么做?


我建议将匿名函数传递给 sort() 方法:

1
2
3
4
5
6
var dates = ['10-Jan-2013','12-Dec-2013','1-Sep-2013','15-Sep-2013'],
    orderedDates = dates.sort(function(a,b){
        return Date.parse(a) > Date.parse(b);
    });

console.log(orderedDates); // ["10-Jan-2013","1-Sep-2013","15-Sep-2013","12-Dec-2013"]
1
2
3
4
5
6
var dates = ['10-Jan-2013', '12-Dec-2013', '1-Sep-2013', '15-Sep-2013'],
  orderedDates = dates.sort(function(a, b) {
    return Date.parse(a) > Date.parse(b);
  });

console.log(orderedDates);

JS Fiddle 演示。

注意使用带引号的日期字符串数组 ['10-Jan-2013','12-Dec-2013','1-Sep-2013','15-Sep-2013']

上面会给你一个日期数组,从最早到最晚列出;如果你只想要最早的,那么使用 orderedDates[0].

修改后的方法,只显示最早的日期——正如问题中所要求的——如下:

1
2
3
4
5
6
var dates = ['10-Jan-2013', '12-Dec-2013', '1-Sep-2013', '15-Sep-2013'],
    earliest = dates.reduce(function (pre, cur) {
        return Date.parse(pre) > Date.parse(cur) ? cur : pre;
    });

console.log(earliest); // 10-Jan-2013
1
2
3
4
5
6
var dates = ['10-Jan-2013', '12-Dec-2013', '1-Sep-2013', '15-Sep-2013'],
  earliest = dates.reduce(function(pre, cur) {
    return Date.parse(pre) > Date.parse(cur) ? cur : pre;
  });

console.log(earliest);

JS Fiddle 演示。

参考文献:

  • Date.parse()
  • Array.prototype.reduce()
  • Array.prototype.sort()


假设您有一组 Date 对象。

1
2
3
4
5
6
7
8
9
10
11
function findEarliestDate(dates){
    if(dates.length == 0) return null;
    var earliestDate = dates[0];
    for(var i = 1; i < dates.length ; i++){
        var currentDate = dates[i];
        if(currentDate < earliestDate){
            earliestDate = currentDate;
        }
    }
    return earliestDate;
}