Skip to content

Instantly share code, notes, and snippets.

@multinerd
Created Sep 21, 2022
Embed
What would you like to do?
/// Weekday: 1 = sunday, 2 = monday, 3 = tuesday, 4 = wednesday, 5 = thursday, 6 = friday, 7 = saturday.
/// WeekDiff: -2 = 2 weeks ago, -1 = 1 week ago, 0 = current week, 1 = next week, 2 = next 2 weeks.
/// Examples:
/// - `getDateForWeekDayInWeek(1, 0)` will return mondays date for the current week.
/// - `getDateForWeekDayInWeek(7, -1)` will return sundays date for the last week.
function getDateForWeekDayInWeek(weekday, weekDiff = 0) {
let d = new Date();
d.setDate(d.getDate() - (d.getDay() + (7 - (weekday - 1))));
weekDiff += 1;
let newDate = new Date(d.setDate(d.getDate() + weekDiff * 7));
return newDate.toLocaleDateString("en-us", {
day: "2-digit",
month: "2-digit",
year: "numeric"
});
}
window.wb = window.wb || {};
window.wb.getDateForWeekDayInWeek = getDateForWeekDayInWeek;
// Debug
console.log(window.wb);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment