【问题标题】:How can I get the nearest date with given day using date-fns?如何使用 date-fns 获取给定日期的最近日期?
【发布时间】:2021-10-28 11:13:59
【问题描述】:

在我的数据库中,我存储了像“sun”这样的一天,现在我正在尝试使用这一天获取一周中最近的一天,我让它与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 实现这一目标?

【问题讨论】:

    标签: javascript date momentjs date-fns


    【解决方案1】:

    您也可以使用 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())
    );

    【讨论】:

      【解决方案2】:

      我使用isSameDayaddDaysstartOfWeeknextDay 修复了这个问题

      const getFirstDateFromDay = () => {
        const dayIndex = days.indexOf(day) as Day
      
        return isSameDay(date, addDays(startOfWeek(date), dayIndex))
          ? date
          : nextDay(date, dayIndex)
      }
      

      【讨论】:

      • days.indexOf(day) as Day 是javascript吗?
      猜你喜欢
      • 1970-01-01
      • 2021-06-25
      • 2020-03-10
      • 2018-09-18
      • 2021-01-29
      • 2021-11-14
      • 1970-01-01
      • 2021-01-23
      • 2019-02-19
      相关资源
      最近更新 更多