Created
October 10, 2024 08:16
-
-
Save dwsmart/ef884bcddf7255a475bf17a4c0fbb495 to your computer and use it in GitHub Desktop.
Get the same day of the week in a previous year
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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