-2

I have an array of dates in ISO format:

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",
  },
];

I need to determine what event (date range) is closest to today, in order to prompt the user to select the most likely event. I need to calculate (with JavaScript) which event’s end_time is closest to today’s date, and return that event. If events are ended, I want to the last event to be the default.


This is the solution that I stumbled upon:

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

It seems to be working! Does this look solid to you?

  • 1
    Show some research at least. One tip: converts the date to a timestamp `date.getTime()` converting your string date to `date` js object. `var myDate = new Date("2015-11-30T14:00:24.082Z"); var result = myDate.getTime();` – Jean Rostan Apr 04 '18 at 19:08
  • most solutions you have seen seems not enough. First result after googling for "work with dates in javascript" is a page containing half your answer, at least: https://www.w3schools.com/js/js_dates.asp – Slavic Apr 04 '18 at 19:11
  • How do you define "closest"? Is it the end time or start time closest to today? Does it matter if it's after today? Or the range includes today? If two ranges are equally distant from today, which is "closest"? The first? Last? There are more questions… – RobG Apr 05 '18 at 10:17

1 Answers1

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]);
Nishant Dixit
  • 5,388
  • 5
  • 17
  • 29
  • Consider explaining how your code works. Your answer appears in the Low Quality posts queue, and the lack of an appropriate explanation is likely to be the main reason for this. – Al.G. Apr 04 '18 at 20:43