我希望能够根据当前日期使用 date-fns 找出过去一周中最近的一天。假设我需要根据当前日期查找过去最近的星期五、星期三、星期四等。
我查看了文档,只能看到这些拖曳方法 https://date-fns.org/docs/closestTo和 https://date-fns.org/v1.29.0/docs/getDay我认为可能会有帮助,但我正在寻找的那个不见了。
有什么想法吗?
最佳答案
// use require or import in your code
// const { getISODay, addDays } = require("date-fns");
const { getISODay, addDays } = dateFns;
function getDayInPast(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,
};
// dayOfWeekMap[dayOfWeek] get the ISODay for the desired dayOfWeek
const targetISODay = dayOfWeekMap[dayOfWeek];
const fromISODay = getISODay(fromDate);
// targetISODay >= fromISODay means we need to trace back to last week
// e.g. target is Wed(3), from is Tue(2)
// hence, need to -7 the account for the offset of a week
const offsetDays =
targetISODay >= fromISODay
? -7 + (targetISODay - fromISODay)
: targetISODay - fromISODay;
return addDays(fromDate, offsetDays);
}
console.log(getDayInPast("Mon"));
console.log(getDayInPast("Tue"));
console.log(getDayInPast("Wed"));
console.log(getDayInPast("Thur"));
console.log(getDayInPast("Fri"));
console.log(getDayInPast("Sat"));
console.log(getDayInPast("Sun"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.min.js"></script>
感谢@giraff 指出上一版本中偏移量的问题
关于javascript - 如何使用 date-fns 查找一周中最近的一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54142402/