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?