To subtract a few days from a date in JavaScript, you need to use setDate()
on a Date
object and decrement the current day of the month – returned by getDate()
– by one or more days.
✋ Update: This post was originally published on my blog decodingweb.dev, where you can read the latest version for a 💯 user experience. ~reza
You can do it in three steps:
Get the day of the month by the
Date.prototype.getDate()
methodTake one or more days from the
getDate()
returned valueUse
Date.prototype.setDate()
to update the object
For instance, to get the date 5
days ago in JavaScript:
// Get the current date
const currentDate = new Date()
// Instantiate another date object to avoid mutating the current date object
const pastDate = new Date(currentDate)
pastDate.setDate(pastDate.getDate() - 5)
console.log(futureDate)
In the above example, we instantiate the pastDate
off the currentDate
for two reasons:
To avoid mutating the original date object (
currentDate
in this case)To guarantee we subtract the days from a date object identical to the original
The getDate()
method returns the day of the month of the date object on which it's called. The return value is an integer number between 1
and 31
.
Next, we subtract 5
from the value returned by getDate()
- and pass it to setDate()
to save the result.
The Date object works smartly when modifying the days. If the result is outside the acceptable range for the respective month, setDate()
will update the Date
object accordingly.
For instance, if it's November 1st, and we take 5 days from it, the result would be October 27th!
Create a helper function to add days to a specific date
To make this functionality reusable, you can create a helper function that accepts a date and an arbitrary number of days to subtract.
function subtractDaysFromDate(currentDate, daysToSubtract) {
daysToSubtract = daysToSubtract || 0
// Instantiate a new object based on the current Date
const pastDate = new Date(currentDate)
// Subtract the number of days
pastDate.setDate(pastDate.getDate() - daysToSubtract)
return pastDate
}
So to subtract 7 days from a date object:
console.log(subtractDaysFromDate(new Date('2022-11-05'), 7))
// expected output: Sat Oct 29 2022 00:00:00 GMT+0100 (Western European Summer Time)
You can also add days to specific date using the same logic. For instance, 5
days from today. All you need to do is to replace the -
operator with the +
operator.
And that's how you can subtract days from a date in JavaScript without a library. I hope you found this guide helpful.
Thanks for reading!
❤️ You might like: