找到最接近的ISO日期(javascript)

时间:2018-04-04 19:05:52

标签: javascript sorting date isodate

我有一系列ISO格式的日期:

const events = [
  {
    start_time: "2015-11-30T14:00:24.082Z",
    end_time: "2015-12-04T07:00:24.093Z",
  },
  {
    start_time: "1970-11-01T00:00:00.000Z",
    end_time: "1970-12-01T00:00:00.000Z",
  },
  {
    start_time: "1983-02-01T00:00:00.000Z",
    end_time: "1983-02-01T00:00:00.000Z",
  },
];

我需要确定哪个事件(日期范围)最接近今天,以便提示用户选择最可能的事件。我需要计算(使用JavaScript)哪个事件的end_time最接近今天的日期,并返回该事件。如果事件结束,我希望最后一个事件成为默认事件。

这是我偶然发现的解决方案:

function determineLikelySelection(events) {
   if (!events.length || !Array.isArray(events)) {
     return {};
   }

   // if all events ended, we'll choose the last one as our default
   const bestEvent = events[events.length - 1];

   const now = Date.now();

   // get the last events end time difference in microseconds
   let closest = Math.abs((new Date(this.bestEvent.end_time)).getTime() - now);

   events.forEach((event) => {
     // event end time in microseconds
     const end = (new Date(event.end_time)).getTime();
     // if end + 1 day is less than now then don't select this one - it's OVER
     if (end + 864000 < now) {
       return;
     }
     // How long ago did this thing end, is it even closer to now or closer than our bestEvent
     if (Math.abs(end - now) < closest) {
       // this is our better match, set it
       closest = Math.abs(end - now);
       const bestEvent = event;
     }
   }
 });
 return bestEvent;
}

似乎工作正常!这看起来很坚固吗?

1 个答案:

答案 0 :(得分:0)

var sortedData = dates.sort(function(a,b){
                 return new Date(b.end_time).getTime()-new Date(a.end_time).getTime()
                 });

console.log(sortedData[0]);