数组中日期的最小/最大

时间:2018-11-10 14:04:02

标签: javascript arrays date

var expenseDates = ["2018-02-06","2018-11-08","2018-11-10","2017-05-02","2017-05-02","2018-11-01"];

var sorted = expenseDates.slice()
.sort(function(a, b) {
   return new Date(a) - new Date(b);
});
    
console.log(sorted.pop()+    '--max');
console.log(sorted.shift()+  '--min');

1 个答案:

答案 0 :(得分:2)

您没有将其转换为日期对象,因为日期采用YYYY-MM-DD格式,日期本身按year => month => day排序。因此,您只需要将输入字符串与localCompare进行比较即可。第一个索引是最小日期,最后一个索引是最大日期

var expenseDates = ["2018-02-06","2018-11-08","2018-11-10","2017-05-02","2017-05-02","2018-11-01"];

    expenseDates = expenseDates.sort(function(a, b) {
        return a.localeCompare(b);
    });

   console.log('--min => ',expenseDates[0]);
   console.log('--max => ', expenseDates[expenseDates.length -1]);

正在工作的jsFiddle演示-https://jsfiddle.net/rpdon5cm/1/