I want to retrieve a date by providing day number of a specific week
Eg
When I say
day: 1
It should provide me:
2023-01-15
What I have tried so far is:
function calculatedDate (day){ let date = new Date(); let dayAtDate = date.getDay(); let dayDiff = day - dayAtDate; if(dayDiff < 0){ dayDiff = 7 + dayDiff; } let desiredDate = date.setDate(date.getDate() + dayDiff); return new Date(desiredDate); } console.log(calculatedDate(1));
Now the problem with above code is that it considers day: 1
as monday, but I want day: 1
to be sunday here.
Can anyone help me with the best possible way here?
Sunday is 0, Monday is 1 here:
function calculatedDate (day) { let date = new Date(); let dayAtDate = date.getDay(); let dayDiff = day - (dayAtDate + 1); // change here if (dayDiff < 0) { dayDiff = 7 + dayDiff; } let desiredDate = date.setDate(date.getDate() + dayDiff); return new Date(desiredDate); } console.log(calculatedDate(1));
How about just -1 the provided day? that should solve it:
function calculatedDate (day){ let date = new Date(); let dayAtDate = date.getDay(); day = day - 1; let dayDiff = day - dayAtDate; if(dayDiff < 0){ dayDiff = 7 + dayDiff; } let desiredDate = date.setDate(date.getDate() + dayDiff); return new Date(desiredDate); } console.log(calculatedDate(1));
You'd probably want to add some validation on the input parameter day
, make sure it's a number and 1 or greater.
The current day will be 0, account for this by making the following change.
if(dayDiff < 0){
dayDiff = 6 + dayDiff;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.