Skip to content

Instantly share code, notes, and snippets.

@dwsmart
Created October 10, 2024 08:16
Show Gist options
  • Save dwsmart/ef884bcddf7255a475bf17a4c0fbb495 to your computer and use it in GitHub Desktop.
Save dwsmart/ef884bcddf7255a475bf17a4c0fbb495 to your computer and use it in GitHub Desktop.
Get the same day of the week in a previous year
// get same day of the week in the last x years ago for specific date.
// Default is 1 year ago, and default date is today, takes account of leap year
function getPreviousYearSameDay(dateToStart = false, years = 1) {
const date = dateToStart ? new Date(dateToStart) : new Date();
const lastYear = new Date(date.getFullYear() - years, date.getMonth(), date.getDate());
const dayDiff = date.getDay() - lastYear.getDay();
return new Date(lastYear.setDate(date.getDate() + dayDiff));
}
console.log(getPreviousYearSameDay('2024-10-10', 1).toISOString()); // 2023-10-11T23:00:00.000Z
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment