返回日期数组中的最新日期 [英] Return the latest date from array of dates

查看:95
本文介绍了返回日期数组中的最新日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的json如下:

  "reviews":[
    {
    "notes": "Great place, perfect location but the best part was the Staff. Thank you so much for making our trip so wonderful!",
    "date": "2015-04-18",
    "rating":{"overall": 100}
    },
    {
    "notes": "I messed up the days I was supposed to be there but they did everything they could to get me a room, which I did. The guy at the front was super nice and then drew me an entire map based off of how much time I had there in Rome. It was extremely helpful and the restaurant he recommends (a friends who you get 10% off of) had good lasagna. Great place for a really reasonable price. Also, the doors do not automatically lock for you room, so just remember to lock your door when you leave. ",
    "date": "2016-04-18",
    "rating":{"overall": 94}
    }
    ]

我正在尝试获取最新日期(最新),以便

I am trying to get the latest date (most recent) so that I can print the associated "notes".

      function highestReview() {
        var maxNumb = [];
        for(var y = 0; y < data.reviews.length; y++){
          maxNumb.push(data.reviews[y].date);
        }
       var latestDate = new Date(Math.max.apply(null, maxNumb));
        console.log(latestDate);

      }
      highestReview();

我正在获取无效日期

推荐答案


按照 docs 如果至少有一个参数不能转换为数字,结果为 NaN ,而 new Date(NaN)将为 无效日期

As per the docs, If at least one of arguments cannot be converted to a number, the result is NaN And new Date(NaN) will be Invalid Date

将日期字符串包装在<$ c中$ c>新日期,同时推入数组。当 DateObject 通过 Number 传递时,表示日期的数值

Wrap the date string in new Date while pushing in array. When DateObject is passed through Number, numeric value representing date will be returned.

var data = {
  "reviews": [{
    "notes": "Great place, perfect location but the best part was the Staff. Thank you so much for making our trip so wonderful!",
    "date": "2015-04-18",
    "rating": {
      "overall": 100
    }
  }, {
    "notes": "I messed up the days I was supposed to be there but they did everything they could to get me a room, which I did. The guy at the front was super nice and then drew me an entire map based off of how much time I had there in Rome. It was extremely helpful and the restaurant he recommends (a friends who you get 10% off of) had good lasagna. Great place for a really reasonable price. Also, the doors do not automatically lock for you room, so just remember to lock your door when you leave. ",
    "date": "2016-04-18",
    "rating": {
      "overall": 94
    }
  }]
};

function highestReview() {
  var maxNumb = [];
  for (var y = 0; y < data.reviews.length; y++) {
    maxNumb.push(new Date(data.reviews[y].date));
  }
  var latestDate = new Date(Math.max.apply(null, maxNumb));
  console.log(latestDate);
}
highestReview();

这篇关于返回日期数组中的最新日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆