Calculating a Date N Days Ago
Here is a simple function that will calculate a date ‘N’ days ago:
The getDate() method retrieves the current day of the month (from 1 to 31), and we subtract ‘N’ from this value. The setDate() method then sets this new value as the day of the month for our date object.
Calculating a Date N Months Ago
To calculate the date ‘N’ months ago, we can use the setMonth() method in combination with the getMonth() method. Here’s a simple function that will calculate the date ‘N’ months ago:
The getMonth() method retrieves the current month (remember, it’s 0-indexed), and we subtract ‘N’ from this value. The setMonth() method then sets this new value as the month for our date object.
Handling Year Rollbacks
While the above solution works well for getting past dates within the current year, it will not work as expected when the subtraction of months crosses over to the previous year(s). The setMonth() method will set the month correctly, but it does not automatically adjust the year.
To handle year rollbacks, we need to take into account the current month and the number of months we want to go back:
This code calculates the new month and year separately, and then sets them using the setFullYear() and setMonth() methods. It takes into account the situation when we need to move to the previous year(s).