I have a function that takes the desired day number and ultimately I want it to be able to return the date of that day in the current week, given the day number it takes. This is my code.
function getDateForDayInWeek(day) {
const today = new Date();
const currentDay = (today.getDay() + 1) % 7;
const adjustedDay = currentDay === 0 ? 6 : currentDay - 1;
const daysToAdjust = (day - adjustedDay + 7) % 7;
today.setDate(today.getDate() + daysToAdjust);
// Formatting the date to YYYY-MM-DDTHH:mm:ss
return today.toISOString().slice(0, 19);
}
console.log(getDateForDayInWeek(6)); // 2024-12-21 ,Saturday
console.log(getDateForDayInWeek(0)); // 2024-12-22 ,Sunday
console.log(getDateForDayInWeek(5)); // 2024-12-27 ,Friday
2
Answers
To get the current weekday’s date in JavaScript, you can use the Date object and manipulate it to get the date of a specific day in the current week based on a given day number.
Here’s the breakdown of the function:
Explanation:
adjustedDay ensures that Sunday is considered as 6 (instead of 0).
toISOString() is used to format the date in a consistent format, and .slice(0, 19) removes the milliseconds part.
This code will return the date for the given day number in the current week.
Try this:
The key difference is that it now correctly calculates the dates for the current week without unnecessary complexity in the day calculations.