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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7143399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:01:37  来源:igfitidea点击:

Min/Max of dates in an array?

javascriptdate

提问by Legend

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?

是否有内置函数来执行此操作,还是我自己编写?

回答by Andrew D.

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));

回答by Legend

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 dev 上测试

回答by Mark Amery

_.minand _.maxwork 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.

_.min_.max处理日期数组;如果您正在使用 Lodash 或 Underscore,请使用它们,如果您还没有使用,请考虑使用 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).

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

回答by lvd

Same as apply, now with spread:

与 apply 相同,现在使用spread

const maxDate = new Date(Math.max(...dates));

(could be a comment on best answer)

(可能是对最佳答案的评论)

回答by Ricardo Tomasi

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

由于日期被转换为 UNIX 纪元(数字),您可以使用 Math.max/min 来查找那些:

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 中测试,但应该在大多数浏览器中工作)

回答by Rudresh Ajgaonkar

**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.apply(null, ArrayOfdates);

回答by Kamil Kie?czewski

ONELINER:

单线

var min= dates.sort((a,b)=>a-b)[0], max= dates.slice(-1)[0];

result in variables minand max, complexity O(nlogn), editable example here. If your array has no-date values (like null) first clean it by dates=dates.filter(d=> d instanceof Date);.

导致变量minmax,复杂度O(nlogn),可编辑示例here。如果您的数组具有无日期值(如null),请先将其清理干净dates=dates.filter(d=> d instanceof Date);

var dates = [];
dates.push(new Date("2011-06-25")); // I change "/" to "-" in "2011/06/25"
dates.push(new Date("2011-06-26")); // because conosle log write dates 
dates.push(new Date("2011-06-27")); // using "-".
dates.push(new Date("2011-06-28"));

var min= dates.sort((a,b)=>a-b)[0], max= dates.slice(-1)[0];

console.log({min,max});

回答by wong2

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

回答by Samdeesh

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 hereand used it as a filter with AngularJS in this codepen

在这里添加了一个普通的 javascript演示,并在此代码笔中将其用作带有 AngularJS 的过滤器

回答by Samdeesh

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

这是本页公认的答案: 在对象数组中查找属性的最大值