5

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

我查看了文档,只能看到我认为可能有帮助的这两个方法https://date-fns.org/docs/closestTohttps://date-fns.org/v1.29.0/docs/getDay我要找的那个不见了。

有什么想法吗?

4

1 回答 1

9
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'));
于 2019-01-11T14:34:48.360 回答