-5

I'm looking for a simple solution that outputs the closest future date from an array of dates I select.

eg. Array = Mon 2nd December 2019, Monday 16th December 2019, Thu 2nd January 2020, Wed 15th January, etc

If current date is eg. '25th December,' then it outputs "Thu 2nd January 2020" as this is the closest future date in the array.

The date format of the array doesn't need to be as-written above, but the output needs to be in normal text. (eg "Thu 2nd Jan 2020")

  • 7
    What have you tried so far to achieve this? – I am L Nov 15 '19 at 12:40
  • Kindly post your effort, then only we can help. – Prabhjot Singh Kainth Nov 15 '19 at 12:42
  • To be honest, I've only recently started doing a js course on Udemy! I only have a few hours a week to learn and I haven't yet got to a stage where I would be able to do write the above myself. Unfortunately, the requirement for this snippet has come up in my business in advance of my ability to fulfil it, so I was hoping a friendly soul with more knowledge than my could give me a leg up? – Dan Segelov Nov 15 '19 at 12:54

1 Answers1

0

Assuming your input array is sorted (and if not, it's easy to make it so), you can do something like the following:

const DAY_NAMES = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const MONTH_NAMES = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

// find the first date that is later than `now` (assumes sorted array of dates)
function getClosestDate(now, dates) {
  for (let date of dates) {
    if (date > now) return date;
  }
}

function formatDate(date) {
  let ordinalSuffix;
  const d = date.getDate();
  switch (d) { // figure out what suffix we need
    case 1: case 21: case 31:
      ordinalSuffix = "st"; break;
    case 2: case 22:
      ordinalSuffix = "nd"; break;
    case 3: case 23:
      ordinalSuffix = "rd"; break;
    default: ordinalSuffix = "th";
  }
  return `${DAY_NAMES[date.getDay()]} ${d}${ordinalSuffix} ${MONTH_NAMES[date.getMonth()]} ${date.getFullYear()}`;
}

const dates = [new Date("2019-12-02"), new Date("2019-12-16"), new Date("2020-01-02"), new Date("2020-01-15")];

const closestDate = getClosestDate(new Date("2019-12-25"), dates);
console.log(closestDate); // 2020-01-02T00:00:00.000Z
console.log(formatDate(closestDate)); // Thu 2nd Jan 2020

If your array of dates is coming from somewhere as strings, it may be useful to parse them into Date objects before processing them further.

Zack Guard
  • 1
  • 3
  • 1
  • Absolutely BRILLIANT! Thanks Zack! – Dan Segelov Nov 15 '19 at 15:14
  • Is it easy to add a second array of dates? I'm trying to get outputs that I can use in sentences like " Order before (output1) for delivery on (output2)" – Dan Segelov Nov 15 '19 at 15:15
  • @Dan That would depend on the business logic; you could for example define two arrays `orderBeforeDates` and `deliveryDates` and pass them into two calls to `getClosestDate()`. – Zack Guard Nov 17 '19 at 09:15