Skip to content

Instantly share code, notes, and snippets.

@multinerd
Created September 21, 2022 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save multinerd/fe7c53f4d3ab91dd0b4805702fc09e1b to your computer and use it in GitHub Desktop.
Save multinerd/fe7c53f4d3ab91dd0b4805702fc09e1b to your computer and use it in GitHub Desktop.
/// 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