Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the nearest date through moment.js?

Dates list:

const datesToBeChecked = [ '2020-07-06', '2020-07-13', '2020-07-20' ]

Date to be checked for

const dateToCheckFor = '2020-07-07';

How can I get the nearest date for the date in the dates array using moment.js?
I want the function to return 2020-07-13 in this case.
I found a couple of answers online but none of them use YYYY-MM-DD format neither moment.js. I want to use moment.js to achieve this, thanks!

like image 244
Cedric Hadjian Avatar asked Oct 26 '25 07:10

Cedric Hadjian


1 Answers

You can use the diff method to compare dates.

const datesToBeChecked = ['2020-07-06', '2020-07-13', '2020-07-20']
const dateToCheckFor = '2020-07-07';

let nearestDate;

datesToBeChecked.forEach(date => {
  let diff = moment(date).diff(moment(dateToCheckFor), 'days');
  if (diff > 0) {
    if (nearestDate) {
      if (moment(date).diff(moment(nearestDate), 'days') < 0) {
        nearestDate = date;
      }
    } else {
      nearestDate = date;
    }
  }
});

console.log(nearestDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>
like image 127
Nidhin Joseph Avatar answered Oct 28 '25 19:10

Nidhin Joseph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!