Home > front end >  What is a cleaner way to subtract a specified number of months from a date that doesn't involve
What is a cleaner way to subtract a specified number of months from a date that doesn't involve

Time:08-25

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

CodePudding user response:

I have a similar code to figuring out if a date is on the last day of the month. Yes you have to start off by creating a new Date object because .setMonth(...) will update the object itself that it is called on. Same as .setDate(...) shown below.

function isLastDayOfMonth(date) {
    var n = new Date(date),
        d = n.getDate();
    n.setDate(d   1);
    return n.getMonth() != date.getMonth();
}

CodePudding user response:

Here is a working version:

export function subtractMonths(numOfMonths: number, date: Date = new Date()) {
  const clonedDate = new Date(date);
  clonedDate.setMonth(date.getMonth() - numOfMonths);

  return clonedDate;
}

If you need to manipulate dates and can use external libs, I suggest to use date-fns

  • Related