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!
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With