I want to be able to find out the nearest Day of the week in the past based on the current date with date-fns. Say I need to find nearest Friday, Wednesday, Thursday etc in the past based on the current date.
I looked in to the documentation and can see only these tow methods https://date-fns.org/docs/closestTo and https://date-fns.org/v1.29.0/docs/getDay that I thought might help but the one I am looking for is missing.
Any thoughts?
// 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>
Thanks @giraff for pointing out the issue about offset in the previous version
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With