Trying to develop a function that takes the current date as input using:
const currDate = new Date()
The goal is to pass this value to a function that subtracts a specific number of months from the current date and returns the result in RFC 3399 format.
Referenced a post here, which provided a function for date subtraction:
export function subtractMonths(numOfMonths: number, date: Date = new Date()) {
date.setMonth(date.getMonth() - numOfMonths);
return date;
}
Encountering an issue when calling the function and formatting it. It changes the date instead of retaining the original value:
const currDate = new Date(); // "2022-08-24T18:26:33.965Z"
const endDate = subtractMonths(6, currDate) // this alters currDate to "2022-02-24T19:26:33.965Z"
const formattedStartDate = endDate.toISOString() // "2022-08-24T18:26:33.965Z"
const formattedEndDate = currDate.toISOString() // "2022-08-24T18:26:33.965Z"
Currently resolving the issue by creating two instances of the Date object, but seeking a more efficient approach to achieve this task.
Edit: Acknowledging the need to duplicate the date objects. Looking for a cleaner method to write the function while maintaining functionality.