Subtract Days and Months from Javascript Date
At some point, we may need to subtract days or months from the Javascript Date Object. Let's say we have a date filter and it has start Date and end Date, but the start date should be the one month less than the current date. It's very easy to implement.
Subtracting Days from a Date
Let's subtract 10 Days from the current date.
var date = new Date();
console.log('Before subtracting -', date);
date.setDate(date.getDate() - 10);
console.log('After subtracting -', date);
// 👉️ Results
// Before subtracting - Thu Jul 28
// After subtracting - Mon Jul 18
Subtracting Months from a Date
Let's subtract 12 months from the current date
var date = new Date();
console.log('Before subtracting -', date);
date.setMonth(date.getMonth() - 12);
console.log('After subtracting -', date);
// 👉️ Results
// Before subtracting - Thu Jul 28 2022
// After subtracting - Wed Jul 28 2021