最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I get the nearest date through moment.js? - Stack Overflow

programmeradmin2浏览0评论

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!

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!

Share Improve this question asked Jun 15, 2020 at 2:45 Cedric HadjianCedric Hadjian 91413 silver badges32 bronze badges 1
  • I suggest you have a look at the countdown library for moment js, this can help you further – Sean Commented Jun 15, 2020 at 2:58
Add a ment  | 

3 Answers 3

Reset to default 7

You can use the diff method to pare 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./ajax/libs/moment.js/2.26.0/moment.min.js"></script>

In my case, I want to find the nearest value. In case, it can not find a larger value in the array then it should return the largest date from the array. Also, Dates Should be verified.

const findNearestDate = (arrayOfDates, findDate) => {
  try {
    let nearestDate, momentsDate;
    if (moment(findDate).isValid()) {
      momentsDate = arrayOfDates.map(date => {
        if (moment(date).isValid()) {
          date = moment(date);
          const diff = moment(date).diff(moment(findDate), 'seconds');
          if (diff >= 0) {
            if (nearestDate) {
              if (moment(date).diff(moment(nearestDate), 'seconds') < 0) {
                nearestDate = date;
              }
            } else {
              nearestDate = date;
            }
          }
        } else {
          date = false;
        }

        return date;
      }).filter(isValid => isValid);
    }

    if (!nearestDate) {
      nearestDate = moment.max(momentsDate);
    }
    return nearestDate.format('YYYY-MM-DD HH:mm:ss');
  } catch (error) {
    console.error(`Error In findNearestDate ${error}`);
    return false;
  }
};


const datesToBeChecked = ['1998-03-16 10:15:00', '1998-03-16 10:15:10', '1998-03-16 09:00:00', '1998-03-16 10:00:00', '1998-03-16 10:00:00', '1998-03-16 10:20:00', '1998-03-16 110:20:00'];

// Remove Below Line if you want to see the warnings
console.warn = () => {};

document.write('1998-03-16 10:15:00 ' + '=>' + findNearestDate(datesToBeChecked, '1998-03-16 10:15:00') + '<br/>');
document.write('1998-03-16 10:18:00 ' + '=>' + findNearestDate(datesToBeChecked, '1998-03-16 10:18:00') + '<br/>');
document.write('1998-03-16 10:23:00 ' + '=>' + findNearestDate(datesToBeChecked, '1998-03-16 21:23:00') + '<br/>');
document.write('1998-03-16 210:23:00 ' + '=>' + findNearestDate(datesToBeChecked, '1998-03-16 210:23:00') + '<br/>');
document.write('1998-03-16 09:23:00 ' + '=>' + findNearestDate(datesToBeChecked, '1998-03-16 09:23:00') + '<br/>');
document.write('1998-03-16 10:20:00 ' + '=>' + findNearestDate(datesToBeChecked, '1998-03-16 10:20:00') + '<br/>');
<script src="https://cdnjs.cloudflare./ajax/libs/moment.js/2.26.0/moment.min.js"></script>

This assumes you are okay with closest date before (could be changed to after) your date:

function get_closest_date(dateToCheckFor){
        var arr = $.map( datesToBeChecked, function (a) {
            return [moment(a).isSameOrBefore(dateToCheckFor) ? a : null ]
        })
        return arr.find(el => el !== null)  // return first valid value
    }
发布评论

评论列表(0)

  1. 暂无评论