How to Subtract Days from Date in JavaScript Easily
To subtract days from a date in JavaScript, use the
Date object and its setDate() method by passing the current day minus the number of days you want to subtract. For example, date.setDate(date.getDate() - daysToSubtract) changes the date correctly.Syntax
The main syntax to subtract days from a date is:
date.getDate(): Gets the current day of the month from theDateobject.date.setDate(day): Sets the day of the month for theDateobject.- Subtract the number of days you want from the current day and set it back.
javascript
date.setDate(date.getDate() - numberOfDays);
Example
This example shows how to subtract 5 days from the current date and print the result.
javascript
const date = new Date(); console.log('Original date:', date.toDateString()); const daysToSubtract = 5; date.setDate(date.getDate() - daysToSubtract); console.log('Date after subtracting 5 days:', date.toDateString());
Output
Original date: Sat Jun 15 2024
Date after subtracting 5 days: Mon Jun 10 2024
Common Pitfalls
One common mistake is trying to subtract days by manipulating the timestamp directly without using setDate(), which can cause errors with month boundaries. Also, forgetting that setDate() automatically adjusts the month and year if the day goes below 1 or above the month's length.
Wrong way example:
let date = new Date(); date = date - 5 * 24 * 60 * 60 * 1000; // This does not update the date object correctly
Right way example:
let date = new Date(); date.setDate(date.getDate() - 5);
Quick Reference
Remember these tips when subtracting days from a date:
- Use
getDate()to get the current day. - Use
setDate()to update the day after subtraction. setDate()handles month and year changes automatically.- Always work with
Dateobjects, not timestamps directly.
Key Takeaways
Use date.setDate(date.getDate() - days) to subtract days safely.
setDate() automatically adjusts months and years when needed.
Avoid manipulating timestamps directly for date arithmetic.
Always work with Date objects for clear and correct results.