Borislav Hadzhiev
Mon Jan 17 2022·2 min read
Photo by Joseph Pearson
To get a date of X days ago, use the setDate()
method to set the date to the
current day of the month minus the number of days, e.g.
daysAgo.setDate(date.getDate() - numOfDays)
. The setDate()
method changes
the day of the month for the given date.
function getDateXDaysAgo(numOfDays, date = new Date()) { const daysAgo = new Date(date.getTime()); daysAgo.setDate(date.getDate() - numOfDays); return daysAgo; } const date = new Date('2022-01-17'); // 👇️ Sat Jan 15 2022 09:28:20 console.log(getDateXDaysAgo(2, date)); // 👇️ Wed Jan 12 2022 09:28:20 console.log(getDateXDaysAgo(5, date));
We created a reusable function that returns a date of X days ago.
The first parameter the function takes is the number of days to subtract from the current day of the month.
The second parameter is the Date
object from which to subtract the number of
days.
If you want to get a date of X days ago from the current date, omit the second parameter when calling the function.
function getDateXDaysAgo(numOfDays, date = new Date()) { const daysAgo = new Date(date.getTime()); daysAgo.setDate(date.getDate() - numOfDays); return daysAgo; } const date = new Date('2022-01-17'); // 👇️ Wed Jan 12 2022 09:37:40 console.log(getDateXDaysAgo(5));
If no Date
object is provided as the second parameter, the function uses the
current date.
In the daysAgo
variable, we created a new Date
object using the timestamp
from the provided Date
.
setDate()
method mutates the Date
it was called on in place.We used the setDate() method to change the day of the month of a date of X days ago.
Note that the Date
object in JavaScript automatically handles the scenario
where a month (and year) has to be rolled back.
Here is an example of that.
function getDateXDaysAgo(numOfDays, date = new Date()) { const daysAgo = new Date(date.getTime()); daysAgo.setDate(date.getDate() - numOfDays); return daysAgo; } const date = new Date('2022-01-17'); // 👇️ Fri Dec 31 2021 console.log(getDateXDaysAgo(17, date));
We got a date of 17 days prior to January 17th, which rolled back the month and
year when creating the Date
object.
If you also want to reset the time component of the date to midnight, you can
use the setHours()
method.
function getDateXDaysAgo(numOfDays, date = new Date()) { const daysAgo = new Date(date.getTime()); daysAgo.setDate(date.getDate() - numOfDays); daysAgo.setHours(0, 0, 0, 0); return daysAgo; } const date = new Date('2022-01-17'); // 👇️ Fri Dec 31 2021 00:00:00 console.log(getDateXDaysAgo(17, date));
The 4 parameters we passed to the setHours()
method are: hours
, minutes
,
seconds
and milliseconds
.
This has the effect to resetting the time component of the Date to midnight.