【问题标题】:How to find the nearest day of the week with date-fns如何使用 date-fns 找到一周中最近的一天
【发布时间】:2019-06-06 03:10:58
【问题描述】:

我希望能够使用 date-fns 根据当前日期找出过去一周中最近的一天。假设我需要根据当前日期查找过去最近的星期五、星期三、星期四等。

我查看了文档,只能看到这两个方法 https://date-fns.org/docs/closestTohttps://date-fns.org/v1.29.0/docs/getDay,我认为它们可能会有所帮助,但我正在寻找的方法却不见了。

有什么想法吗?

【问题讨论】:

    标签: javascript date-fns


    【解决方案1】:
    const { getISODay, addDays } = require('date-fns');
    
    function getClosestDayOfLastWeek(dayOfWeek, fromDate = new Date()) {
        // follow the getISODay format (7 for Sunday, 1 for Monday)
        const dayOfWeekMap = {
            Mon: 1,
            Tue: 2,
            Wed: 3,
            Thur: 4,
            Fri: 5,
            Sat: 6,
            Sun: 7,
        };
    
        // -7 means last week
        // dayOfWeekMap[dayOfWeek] get the ISODay for the desired dayOfWeek
    
        // e.g. If today is Sunday, getISODay(fromDate) will returns 7
        // if the day we want to find is Thursday(4), apart from subtracting one week(-7),
        // we also need to account for the days between Sunday(7) and Thursday(4)
        // Hence we need to also subtract (getISODay(fromDate) - dayOfWeekMap[dayOfWeek])
        const offsetDays = -7 - (getISODay(fromDate) - dayOfWeekMap[dayOfWeek]);
    
        return addDays(fromDate, offsetDays);
    }
    
    console.log(getClosestDayOfLastWeek('Mon'));
    

    【讨论】:

      猜你喜欢
      • 2011-06-14
      • 1970-01-01
      • 2018-04-03
      • 1970-01-01
      • 2021-11-08
      • 2021-10-28
      • 1970-01-01
      • 2014-03-08
      • 2021-10-18
      相关资源
      最近更新 更多