I am trying to create a function that will take in the current date using something like this:
const currDate = new Date()
and I want to be able to pass that value into a function that subtracts the current date from a specific number of months and this function should return an the result using RFC 3399 format
I have looked at this post here and used a function from the post to do the subtraction of dates:
export function subtractMonths(numOfMonths: number, date: Date = new Date()) {
date.setMonth(date.getMonth() - numOfMonths);
return date;
}
the problem is when I call the function and format it. It doesn't keep the same results, and changes the date to the current date:
const currDate = new Date(); // "2022-08-24T18:26:33.965Z"
const endDate = subtractMonths(6, currDate) // this changes the value of 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"
I am able to work around this by creating two instances of the Date object and doin the operation that way, but I feel as though there is a cleaner way to do this but don't know how I would go about doing that.
Edit: I understand why I have to make copies of the date. The issue as stated in the title was trying to find a cleaner way to write the function, as I already have code that works and solves the problem.