Categories
JavaScript Answers

How to subtract days, months, years from a date in JavaScript?

Spread the love

Sometimes, we want to subtract days, months, years from a date in JavaScript.

In this article, we’ll look at how to subtract days, months, years from a date in JavaScript.

How to subtract days, months, years from a date in JavaScript?

To subtract days, months, years from a date in JavaScript, we can call setDate, setMonth, and setFullYear.

For instance, we write

const createDate = (days, months, years) => {
  const date = new Date();
  date.setDate(date.getDate() + days);
  date.setMonth(date.getMonth() + months);
  date.setFullYear(date.getFullYear() + years);
  return date;
};

to define the createDate function.

In it, we create a Date object.

We call setDate with the date value with days added to it to add the number of days to the current date, which we get from getDate.

We call setMonth with the date value with days added to it to add the number of months to the current date, which we get from getMonth.

And we call setFullYear with the date value with days added to it to add the number of years to the current date, which we get from getFullYear.

Finally, we return the date with the values added.

We call createDate with negative values for each argument to subtract them.

Conclusion

To subtract days, months, years from a date in JavaScript, we can call setDate, setMonth, and setFullYear.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to subtract days, months, years from a date in JavaScript?”

Hope this will help me somehow, thanks for sharing this, I was looking for something like this for some hours

Leave a Reply

Your email address will not be published. Required fields are marked *