Home > Blockchain >  Searching for the closest date in an array of dates in JavaScript
Searching for the closest date in an array of dates in JavaScript

Time:09-07

I have been trying to search for the closest date in an array of given Dates

This is the array:

[
 'September 01',
 'September 06',
 'September 08',
 'September 13',
 'September 15',
 'September 20',
 'September 22', 
 'September 27', 
 'September 29',
 'October 04',
 'October 06', 
 'October 11',
 'October 13'
]

For example today's date is 'September 07' and I want the output to be 'September 08'

The format of the dates can not be changed

if it is possible to make it work for any given array with these date format

I tried the following:

-separating the month from the day

-Incrementing the value of the day if not found

But this advance creates a logical error when it comes to the end of the month since no Date will be returned on -for example- September 29

CodePudding user response:

It seems like you want the next date, not the "nearest" date. For example, I'm going to assume an input of "September 02" should return "September 06". There are a few steps to get there, so let's start.

First, take your original array and use Date to get milliseconds since January 1, 1970, 00:00:00 UTC. If you've not used Javascript's Date much, that might seem weird, but that's what lots of date calculates use. There's no year given in your example, so I'll assume they are this year, or your search doesn't make much sense.

const DateHaystack = ['September 01', 'September 06', 'September 08', 'September 13', 'September 15', 'September 20', 'September 22', 'September 27', 'September 29', 'October 04', 'October 06', 'October 11', 'October 13', 'October 18', 'October 20', 'October 25', 'October 27', 'November 01', 'November 03', 'November 08', 'November 10', 'November 15', 'November 17', 'November 22', 'November 24', 'November 29', 'December 01', 'December 06', 'December 08'];

const currentYear = new Date().getFullYear();

const DateInMs = DateHaystack.map(DateString => Date.parse(DateString   ", "   currentYear))

Now, we need the same for today (or whatever date you're using as your search point.)

const Today = Date.parse(new Date())

Ok, so we know when all your dates are in the array, and we know when today is, in terms of ms from 1970. Next, filter all the dates that are smaller than today. From the result of that, find the minimum value. That'll be the next upcoming day.

const UpcomingDayInMs = Math.min(...DateInMs.filter(DateNumber => Today < DateNumber));

And finally, parse that into a date, and pull the month and date.

const Months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

const UpcomingDay = new Date(UpcomingDayInMs)
const UpcomingDayString = `${Months[UpcomingDay.getMonth()]} ${UpcomingDay.getDate()}`;

UpcomingDayString should hold the string you want now.

CodePudding user response:

you can convert strings to date then compare and then send results back again in string like follows

const inputDatesArray = ['September 01', 'September 06', 'September 08', 'September 13', 'September 15', 'September 20', 'September 22', 'September 27', 'September 29', 'October 04', 'October 06', 'October 11', 'October 13', 'October 18', 'October 20', 'October 25', 'October 27', 'November 01', 'November 03', 'November 08', 'November 10', 'November 15', 'November 17', 'November 22', 'November 24', 'November 29', 'December 01', 'December 06', 'December 08']


function getNearestDate(inputDate, datesArray){
    const dates = datesArray.map(dateString => new Date(dateString));
    const currentDate = new Date(inputDate)
    let nearestDateIndex = 0;
    let minDaysBetweenDates = Infinity;
    dates.forEach((date, index) => {
        const diffTime = Math.abs(date - currentDate);
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        if(diffDays <= minDaysBetweenDates){
            nearestDateIndex = index;
            minDaysBetweenDates = diffDays
        }
    });
    return datesArray[nearestDateIndex];
}

console.log(getNearestDate('September 07', inputDatesArray));

CodePudding user response:

This code returns the closest date after today.
This checks every date in the array and adds 1 day when not found.
Eventually it returns the closest date.

For example today's date is 'September 07' and The output is 'September 08

If you want the current day also included, then set var plus = 0

var dates = [
 'September 01',
 'September 06',
 'September 08',
 'September 13',
 'September 15',
 'September 20',
 'September 22', 
 'September 27', 
 'September 29',
 'October 04',
 'October 06', 
 'October 11',
 'October 13'
]

function getDate(){   
  var plus = 1;
  var searching = true;
  while(searching)
  {
    var date  = new Date();  // today
    date.setDate(date.getDate()   plus);
    var month = date.toLocaleString('default', { month: 'long' });
    var day   = date.getDate();
    if(month <= 9)
    {
      month = '0' month;
    }
    if(day <= 9)
    {
      day = '0' day;
    }
    if(dates.includes(month  " " day))
    {
      searching = false;
      return month  " " day;
    }
    else
    {
      plus  ;
    }
  }
}

console.log(getDate());

CodePudding user response:

You can calculate the absolute difference between dates and take the smaller one:

const dates = ['September 01', 'September 06', 'September 08', 'September 13', 'September 15', 'September 20', 'September 22', 'September 27', 'September 29', 'October 04', 'October 06', 'October 11', 'October 13', 'October 18', 'October 20', 'October 25', 'October 27', 'November 01', 'November 03', 'November 08', 'November 10', 'November 15', 'November 17', 'November 22', 'November 24', 'November 29', 'December 01', 'December 06', 'December 08'];

const mdToday = new Date().toLocaleDateString("en-US", { month: 'long', day:'2-digit' }); // 'September 07'
const today = new Date(mdToday); // Fri Sep 07 2001 00:00:00 GMT 0500 (GMT 05:00)

const result = dates.reduce((acc, mdDate) => {
  const date = new Date(mdDate);
  const diff = Math.abs(today - date);
  if (diff < acc.diff) {
    acc.date = mdDate;
    acc.diff = diff;
  }
  return acc;
}, { date: '', diff: Infinity })
.date;
  
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0 }

  • Related