如何使用 date-fns 获取给定日期的最近日期?

How can I get the nearest date with given day using date-fns?

在我的数据库中,我存储了像“太阳”这样的一天,现在我正在尝试使用这一天获取最近的一周中的一天,我让它与 moment

一起工作
getActualDate() {
  const days = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']
  const date = moment.utc().startOf('day')
  const expectedDay = days.indexOf(this.day) // "sun"

  date.days(expectedDay)

  // If later than given day of the week, move to next week
  if (date.days() < moment().days()) {
    date.add(7, 'days')
  }

  return date.toDate()
}

如何使用 date-fns 实现此目的?

我使用 isSameDayaddDaysstartOfWeeknextDay

解决了这个问题
const getFirstDateFromDay = () => {
  const dayIndex = days.indexOf(day) as Day

  return isSameDay(date, addDays(startOfWeek(date), dayIndex))
    ? date
    : nextDay(date, dayIndex)
}

您也可以使用 POJS。应测试输入值,也许还应接受日期。

/* Return next instance of day >= today
 * @param {string} day : 3 letter lower case abbreviation of day name
 * @returns {Date} next instance of day that is >= today
 */
function getDay(day) {
  let days = {sun:0, mon:1, tue:2, wed:3, thu:4, fri:5, sat:6};
  let idx = days[day.toLowerCase().substr(0,3)];
  let today = new Date();
  // Zero time and copy today
  let then = new Date(today.setHours(0,0,0,0));
  // Set then to day in current week
  then.setDate(then.getDate() - then.getDay() + idx);
  // If then is before today, add 7 days. Otherwise, return then
  return then < today ? new Date(then.setDate(then.getDate() + 7)) : then;
}


['sun','mon','tue','wed','thu','fri','sat'].forEach(day =>
  console.log(getDay(day).toString())
);