Moment 在日期数组中获取下一个日期

Moment get next date in arrays of dates

我有一个格式为 March 1stMay 2nd 的日期数组,我想使用 moment.js 遍历这些日期并找出最接近的日期nodejs 中的当前日期。

我们可以使用 Array.reduce 来查找离当前日期最近的日期。我们解析每个日期以获取时刻实例,然后获取与当前日期的绝对偏移量。如果这低于最接近的值,我们将替换它。

const dates = ["January 1st", "March 28th", "April 12th", "April 25th", "May 2nd", "September 8th"];

const now = moment();
const nearestDate = dates.reduce((nearest, dateStr) => {
    const momentDate = moment(dateStr, "MMMM D");
    const timeFromNow = Math.abs(momentDate - now);
    const nearestTimeFromNow = Math.abs(nearest - now);
    
    if (!nearestTimeFromNow || timeFromNow < nearestTimeFromNow) { 
        nearest = momentDate;
    }
    
    return nearest;
})

console.log("Nearest date to now:", nearestDate.format("MMMM Do"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script> 

必须循环数组中的每个元素,并计算数组元素日期与现在(moment())之间的绝对差值(Math.abs())。 您必须指定数组元素的格式,在这种情况下,时刻格式为 MMMM Do.

const arr = ['March 1st', 'April 1st', 'April 28th', 'May 1st', 'May 2nd', 'September 26th'];

let lastDiff;
let nearest;

for (const date of arr) {
  const diff = Math.abs(moment(date, 'MMMM Do').diff(moment(), 'days'));

  if (lastDiff === undefined || lastDiff > diff) {
    lastDiff = diff;
    nearest = date;
  }
}

console.log(nearest)
console.log(moment(nearest, 'MMMM Do').format())

此方法认为年份与现在相同。