数组中日期的最小/最大值?

时间:2022-07-05 04:54:46

How can I find out the min and the max date from an array of dates? Currently, I am creating an array like this:

如何从一个日期数组中找出最小和最大日期?目前,我正在创建一个这样的数组:

var dates = [];
dates.push(new Date("2011/06/25"))
dates.push(new Date("2011/06/26"))
dates.push(new Date("2011/06/27"))
dates.push(new Date("2011/06/28"))

Is there a built-in function to do this or am I to write my own?

有一个内置的函数来做这件事,还是我自己写?

10 个解决方案

#1


97  

Code is tested with IE,FF,Chrome and works properly:

代码使用IE、FF、Chrome进行测试,工作正常:

var dates=[];
dates.push(new Date("2011/06/25"))
dates.push(new Date("2011/06/26"))
dates.push(new Date("2011/06/27"))
dates.push(new Date("2011/06/28"))
var maxDate=new Date(Math.max.apply(null,dates));
var minDate=new Date(Math.min.apply(null,dates));

#2


45  

Something like:

喜欢的东西:

var min = dates.reduce(function (a, b) { return a < b ? a : b; }); 
var max = dates.reduce(function (a, b) { return a > b ? a : b; });

Tested on Chrome 15.0.854.0 dev

在Chrome 15.0.854.0上测试

#3


17  

_.min and _.max work on arrays of dates; use those if you're using Lodash or Underscore, and consider using Lodash (which provides many utility functions like these) if you're not already.

_。分钟,_。最大限度地处理日期数组;如果您正在使用Lodash或下划线,请使用它们,如果您还没有使用的话,请考虑使用Lodash(它提供了许多类似的实用函数)。

For example,

例如,

_.min([
    new Date('2015-05-08T00:07:19Z'),
    new Date('2015-04-08T00:07:19Z'),
    new Date('2015-06-08T00:07:19Z')
])

will return the second date in the array (because it is the earliest).

将返回数组中的第二个日期(因为它是最早的日期)。

#4


8  

Since dates are converted to UNIX epoch (numbers), you can use Math.max/min to find those:

由于日期被转换为UNIX纪元(数字),您可以使用数学。找到这些最大值/最小值:

var maxDate = Math.max.apply(null, dates)
// convert back to date object
maxDate = new Date(maxDate)

(tested in chrome only, but should work in most browsers)

(仅在chrome中测试过,但在大多数浏览器中都可以使用)

#5


2  

function sortDates(a, b)
{
    return a.getTime() - b.getTime();
}

var dates = [];

dates.push(new Date("2011/06/26"))
dates.push(new Date("2011/06/28"))
dates.push(new Date("2011/06/25"))
dates.push(new Date("2011/06/27"))

var sorted = dates.sort(sortDates);
var minDate = sorted[0];
var maxDate = sorted[sorted.length-1];

Demo: http://jsfiddle.net/AlienWebguy/CdXTB/

演示:http://jsfiddle.net/AlienWebguy/CdXTB/

#6


1  

var max_date = dates.sort(function(d1, d2){
    return d2-d1;
})[0];

#7


0  

**Use Spread Operators| ES6 **

**使用扩展操作| ES6 **

let datesVar = [ 2017-10-26T03:37:10.876Z,
  2017-10-27T03:37:10.876Z,
  2017-10-23T03:37:10.876Z,
  2015-10-23T03:37:10.876Z ]

Math.min(...datesVar);

That will give the minimum date from the array.

这将给出数组的最小日期。

Its shorthand Math.min.apply(null, ArrayOfdates);

速记Math.min。应用(null,ArrayOfdates);

#8


0  

The above answers do not handle blank/undefined values to fix this I used the below code and replaced blanks with NA :

上面的答案不处理空白/未定义的值来修复这个问题,我使用了下面的代码并用NA替换了空格:

function getMax(dateArray, filler) {
      filler= filler?filler:"";
      if (!dateArray.length) {
        return filler;
      }
      var max = "";
      dateArray.forEach(function(date) {
        if (date) {
          var d = new Date(date);
          if (max && d.valueOf()>max.valueOf()) {
            max = d;
          } else if (!max) {
            max = d;
          }
        }
      });
      return max;
    };
console.log(getMax([],"NA"));
console.log(getMax(datesArray,"NA"));
console.log(getMax(datesArray));

function getMin(dateArray, filler) {
 filler = filler ? filler : "";
  if (!dateArray.length) {
    return filler;
  }
  var min = "";
  dateArray.forEach(function(date) {
    if (date) {
      var d = new Date(date);
      if (min && d.valueOf() < min.valueOf()) {
        min = d;
      } else if (!min) {
        min = d;
      }
    }
  });
  return min;
}

console.log(getMin([], "NA"));
console.log(getMin(datesArray, "NA"));
console.log(getMin(datesArray));

I have added a plain javascript demo here and used it as a filter with AngularJS in this codepen

我在这里添加了一个普通的javascript演示,并在这个代码页中使用它作为AngularJS的过滤器

#9


-1  

This is a particularly great way to do this (you can get max of an array of objects using one of the object properties): Math.max.apply(Math,array.map(function(o){return o.y;}))

这是一种特别好的方法(您可以使用对象属性之一获得对象数组的最大值):Math.max.apply(Math、array.map(function(o){return o.y;}))

This is the accepted answer for this page: Finding the max value of an attribute in an array of objects

这是这个页面的公认答案:在一个对象数组中找到一个属性的最大值。

#10


-1  

Using Moment, Underscore and jQuery, to iterate an array of dates.

使用Moment、下划线和jQuery来迭代一系列日期。

Sample JSON:

示例JSON:

"workerList": [{        
        "shift_start_dttm": "13/06/2017 20:21",
        "shift_end_dttm": "13/06/2017 23:59"
    }, {
        "shift_start_dttm": "03/04/2018 00:00",
        "shift_end_dttm": "03/05/2018 00:00"        
    }]

Javascript:

Javascript:

function getMinStartDttm(workerList) {  
    if(!_.isEmpty(workerList)) {
        var startDtArr = [];
        $.each(d.workerList, function(index,value) {                
            startDtArr.push(moment(value.shift_start_dttm.trim(), 'DD/MM/YYYY HH:mm')); 
         });            
         var startDt = _.min(startDtArr);           
         return start.format('DD/MM/YYYY HH:mm');
    } else {
        return '';
    }   
}

Hope it helps.

希望它可以帮助。

#1


97  

Code is tested with IE,FF,Chrome and works properly:

代码使用IE、FF、Chrome进行测试,工作正常:

var dates=[];
dates.push(new Date("2011/06/25"))
dates.push(new Date("2011/06/26"))
dates.push(new Date("2011/06/27"))
dates.push(new Date("2011/06/28"))
var maxDate=new Date(Math.max.apply(null,dates));
var minDate=new Date(Math.min.apply(null,dates));

#2


45  

Something like:

喜欢的东西:

var min = dates.reduce(function (a, b) { return a < b ? a : b; }); 
var max = dates.reduce(function (a, b) { return a > b ? a : b; });

Tested on Chrome 15.0.854.0 dev

在Chrome 15.0.854.0上测试

#3


17  

_.min and _.max work on arrays of dates; use those if you're using Lodash or Underscore, and consider using Lodash (which provides many utility functions like these) if you're not already.

_。分钟,_。最大限度地处理日期数组;如果您正在使用Lodash或下划线,请使用它们,如果您还没有使用的话,请考虑使用Lodash(它提供了许多类似的实用函数)。

For example,

例如,

_.min([
    new Date('2015-05-08T00:07:19Z'),
    new Date('2015-04-08T00:07:19Z'),
    new Date('2015-06-08T00:07:19Z')
])

will return the second date in the array (because it is the earliest).

将返回数组中的第二个日期(因为它是最早的日期)。

#4


8  

Since dates are converted to UNIX epoch (numbers), you can use Math.max/min to find those:

由于日期被转换为UNIX纪元(数字),您可以使用数学。找到这些最大值/最小值:

var maxDate = Math.max.apply(null, dates)
// convert back to date object
maxDate = new Date(maxDate)

(tested in chrome only, but should work in most browsers)

(仅在chrome中测试过,但在大多数浏览器中都可以使用)

#5


2  

function sortDates(a, b)
{
    return a.getTime() - b.getTime();
}

var dates = [];

dates.push(new Date("2011/06/26"))
dates.push(new Date("2011/06/28"))
dates.push(new Date("2011/06/25"))
dates.push(new Date("2011/06/27"))

var sorted = dates.sort(sortDates);
var minDate = sorted[0];
var maxDate = sorted[sorted.length-1];

Demo: http://jsfiddle.net/AlienWebguy/CdXTB/

演示:http://jsfiddle.net/AlienWebguy/CdXTB/

#6


1  

var max_date = dates.sort(function(d1, d2){
    return d2-d1;
})[0];

#7


0  

**Use Spread Operators| ES6 **

**使用扩展操作| ES6 **

let datesVar = [ 2017-10-26T03:37:10.876Z,
  2017-10-27T03:37:10.876Z,
  2017-10-23T03:37:10.876Z,
  2015-10-23T03:37:10.876Z ]

Math.min(...datesVar);

That will give the minimum date from the array.

这将给出数组的最小日期。

Its shorthand Math.min.apply(null, ArrayOfdates);

速记Math.min。应用(null,ArrayOfdates);

#8


0  

The above answers do not handle blank/undefined values to fix this I used the below code and replaced blanks with NA :

上面的答案不处理空白/未定义的值来修复这个问题,我使用了下面的代码并用NA替换了空格:

function getMax(dateArray, filler) {
      filler= filler?filler:"";
      if (!dateArray.length) {
        return filler;
      }
      var max = "";
      dateArray.forEach(function(date) {
        if (date) {
          var d = new Date(date);
          if (max && d.valueOf()>max.valueOf()) {
            max = d;
          } else if (!max) {
            max = d;
          }
        }
      });
      return max;
    };
console.log(getMax([],"NA"));
console.log(getMax(datesArray,"NA"));
console.log(getMax(datesArray));

function getMin(dateArray, filler) {
 filler = filler ? filler : "";
  if (!dateArray.length) {
    return filler;
  }
  var min = "";
  dateArray.forEach(function(date) {
    if (date) {
      var d = new Date(date);
      if (min && d.valueOf() < min.valueOf()) {
        min = d;
      } else if (!min) {
        min = d;
      }
    }
  });
  return min;
}

console.log(getMin([], "NA"));
console.log(getMin(datesArray, "NA"));
console.log(getMin(datesArray));

I have added a plain javascript demo here and used it as a filter with AngularJS in this codepen

我在这里添加了一个普通的javascript演示,并在这个代码页中使用它作为AngularJS的过滤器

#9


-1  

This is a particularly great way to do this (you can get max of an array of objects using one of the object properties): Math.max.apply(Math,array.map(function(o){return o.y;}))

这是一种特别好的方法(您可以使用对象属性之一获得对象数组的最大值):Math.max.apply(Math、array.map(function(o){return o.y;}))

This is the accepted answer for this page: Finding the max value of an attribute in an array of objects

这是这个页面的公认答案:在一个对象数组中找到一个属性的最大值。

#10


-1  

Using Moment, Underscore and jQuery, to iterate an array of dates.

使用Moment、下划线和jQuery来迭代一系列日期。

Sample JSON:

示例JSON:

"workerList": [{        
        "shift_start_dttm": "13/06/2017 20:21",
        "shift_end_dttm": "13/06/2017 23:59"
    }, {
        "shift_start_dttm": "03/04/2018 00:00",
        "shift_end_dttm": "03/05/2018 00:00"        
    }]

Javascript:

Javascript:

function getMinStartDttm(workerList) {  
    if(!_.isEmpty(workerList)) {
        var startDtArr = [];
        $.each(d.workerList, function(index,value) {                
            startDtArr.push(moment(value.shift_start_dttm.trim(), 'DD/MM/YYYY HH:mm')); 
         });            
         var startDt = _.min(startDtArr);           
         return start.format('DD/MM/YYYY HH:mm');
    } else {
        return '';
    }   
}

Hope it helps.

希望它可以帮助。