iamrobin.
iamrobin.

Reputation: 1634

moment.js – get next existing day of array

I have an array filled with different days:

let days = ["2018-09-02", "2018-10-06", "2018-10-12", "2018-10-24", "2018-11-02", "2018-11-04"];

How can I detect which of those days is the closest day in the future from today?

My current state can detect, if tomorrow is part of the array but I don't know how to get the closest day in the future when tomorrow doesn't exist.

let nextDay = day.add(1, 'days').format('YYYY-MM-DD');

for (let i = 0; i < days.length; i++) {
  if (day[i] === nextDay) {
    // next day is part of the array
    console.log(nextDay);
  } 
}

Upvotes: 0

Views: 534

Answers (2)

T. Dirks
T. Dirks

Reputation: 3676

A possibility would be to subtract each date from the current date and see which date is the least positive days away.

Example:

let days = ["2018-09-02", "2018-10-06", "2018-10-12", "2018-10-30", "2018-11-02", "2018-11-04", "2019-01-01"];
let curDay = moment().format('YYYY-MM-DD');
let closestDay;
let closestDiff;
for (let i = 0; i < days.length; i++) {
  let diff = moment(days[i]).diff(curDay, 'days'); 
  if(diff > 0){
    if(closestDiff === undefined) {
      closestDay = days[i];
      closestDiff = diff;
    } else if(diff < closestDiff) {
      closestDay = days[i];
      closestDiff = diff;
    }
  }
}
if(closestDay === undefined) closestDay = "no days found in the future";
document.getElementById("closest-future").innerHTML = closestDay;
<!DOCTYPE html>
<html>

  <head>
    <script data-require="[email protected]" data-semver="2.14.1" src="https://npmcdn.com/[email protected]"></script>
  </head>

  <body>
    <div>Shortest date in the future is: <span id='closest-future'></span></div>
  </body>

</html>

Upvotes: 1

str
str

Reputation: 44969

Assuming the array is sorted, you can do the following:

let days = ["2018-09-02", "2018-10-06", "2018-10-12", "2018-10-24", "2018-11-02", "2018-11-04"];
let today = moment().format('YYYY-MM-DD');
console.log(days.find(d => d > today));
<script src="https://cdn.jsdelivr.net/npm/[email protected]/moment.min.js"></script>

Upvotes: 1

Related Questions