javascript - 返回日期数组中的最新日期

标签 javascript date

我的 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}
    }
    ]

我正在尝试获取最新日期(最近的),以便我可以打印相关的“注释”。

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

我收到“无效日期”

最佳答案

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

将日期字符串包装在new Date中,同时插入数组。当DateObject通过Number传递时,将返回代表日期的数值。

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

关于javascript - 返回日期数组中的最新日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36838689/

相关文章:

javascript - 全局 jQuery 对话框变量无法正常工作

javascript - 将 Nodejs 服务器转换为 Node 模块

javascript - 如何获取 00 :00:00 timestamp 的日期

javascript - jQuery .data() 从存储的数组中删除项目

javascript - AngularJS - $emit 仅在其当前范围内有效?

javascript - 从音频文件输入创建MediaElementSource?

mysql - 填补月份空白

python - 根据日期对 CSV 文件进行排序

r - 如何在R中找到日期的 "origin"

javascript - Picktime 时间选择器在启用后不禁用时间