I would like to get the date (YYYY-MM-DD in format) for the last "Wednesday" or "Saturday" or any day that user passes. It could either be from this week or last week, but the latest Wednesday, Thursday etc. For example today is Jan 26th Thursday. Last wednesday would be 2023-01-25, last Thursday would be 2023-01-19, last Saturday would be 2023-01-21 etc.
I checked date-fns
which has startOfWeek
method. But the add
function doesn't seem to take negative numbers for me to add -2, -3 etc. I am new to Typescript and would appreciate any help, guidance.
CodePudding user response:
Its almost Javascript, There are nothing much related to Typescript, Check this:
function getLastGivenDay(day: string): string {
const today = new Date();
const todayDay = today.getDay();
const dayIndex = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"].indexOf(day);
let lastGivenDay = new Date();
lastGivenDay.setDate(today.getDate() - (todayDay - dayIndex) % 7);
if (todayDay < dayIndex || todayDay === dayIndex) {
lastGivenDay.setDate(lastGivenDay.getDate() - 7);
}
return lastGivenDay.toISOString().slice(0, 10);
}