如何使用javascript/jquery从数组中获取最大和最小日期?

use*_*384 2 javascript jquery datetime date

我想从json数组得到最小和最大日期:

我的代码

$.getJSON(url, function (data) {
    var dates = Object.keys( data['data']['horodate'] ).map(function ( key ) {
        return data['data']['horodate'][key].replace(/\-/g,'/' ) 
    });
    var min = new Date(Math.min.apply( null, dates ));
    var max =  new Date(Math.max.apply( null, dates));
});
Run Code Online (Sandbox Code Playgroud)

data 数组是:

Array [ 
    "2016/10/13 00:00:00", 
    "2016/10/13 00:30:00", 
    "2016/10/13 01:00:00", 
    "2016/10/13 01:30:00", 
    "2016/10/13 02:00:00", 
    "2016/10/13 02:30:00", 
    "2016/10/13 03:00:00", 
    "2016/10/13 03:30:00", 
    "2016/10/13 04:00:00", 
    "2016/10/13 04:30:00"
]
Run Code Online (Sandbox Code Playgroud)

但我有一个错误:Invalid date.你能帮助我吗 ?

Pra*_*lan 5

使用Array#sort自定义排序功能,并获得最后一个(max)和第(分钟)值.

data = ["2016/10/13 00:00:00", "2016/10/13 00:30:00", "2016/10/13 01:00:00", "2016/10/13 01:30:00", "2016/10/13 02:00:00", "2016/10/13 02:30:00", "2016/10/13 03:00:00", "2016/10/13 03:30:00", "2016/10/13 04:00:00", "2016/10/13 04:30:00"];

var sorted = data.slice() // copy the array for keeping original array with order
  // sort by parsing them to date
  .sort(function(a, b) {
    return new Date(a) - new Date(b);
  });

// get the first and last values
console.log(
  'max :', sorted.pop(), 'min :', sorted.shift()
);
Run Code Online (Sandbox Code Playgroud)


或者用一个简单的Array#forEach循环.

data = ["2016/10/13 00:00:00", "2016/10/13 00:30:00", "2016/10/13 01:00:00", "2016/10/13 01:30:00", "2016/10/13 02:00:00", "2016/10/13 02:30:00", "2016/10/13 03:00:00", "2016/10/13 03:30:00", "2016/10/13 04:00:00", "2016/10/13 04:30:00"];

// initially set max and min as first element
var max = data[0],
  min = data[0];

// iterate over array values and update min & max
data.forEach(function(v) {
  max = new Date(v) > new Date(max)? v: max;
  min = new Date(v) < new Date(min)? v: min;
});

console.log('max :', max, 'min :', min);
Run Code Online (Sandbox Code Playgroud)