Borislav Hadzhiev
Last updated: Jan 21, 2022
Photo from Unsplash
To add weeks to a date:
getDate()
method to get the day of the month of the specific date.setDate()
method to set the day of the month for the date.setDate
method takes the day of the month as a parameter and sets the
value for the date.function addWeeks(numOfWeeks, date = new Date()) { date.setDate(date.getDate() + numOfWeeks * 7); return date; } // Add 2 weeks to current Date console.log(addWeeks(2)); // 👇️ Mon Feb 28 2022 console.log(addWeeks(2, new Date('2022-02-14')));
We created a reusable function that takes the number of weeks and a Date
object and adds the weeks to the date.
If no Date
object is provided to the function, it uses the current date.
The
getDate()
method returns an integer between 1
and 31
that represents the day of the
month for the date.
7
days for each week.The
setDate()
method takes a number that represents the day of the month as a parameter and
sets the value on the Date
.
The JavaScript Date
object automatically takes care of rolling over the month
and/or year, if adding X weeks to the date increments the month and year.
const date = new Date('2022-02-01'); console.log(date); // 👉️ Tue Feb 01 2022 date.setDate(date.getDate() + 4 * 7); console.log(date); // 👉️ Tue Mar 01 2022
This is very convenient for us because we don't have to worry about the scenario where adding X weeks pushes us into the next month/year.
setDate
method mutates the Date
object it was called on. If you don't want to change the Date
in place, you can create a copy of it before calling the method.function addWeeks(numOfWeeks, date = new Date()) { const dateCopy = new Date(date.getTime()); dateCopy.setDate(dateCopy.getDate() + numOfWeeks * 7); return dateCopy; } const date = new Date('2022-02-13'); const result = addWeeks(2, date); console.log(result); // 👉️ Sun Feb 27 2022 console.log(date); // 👉️ Sun Feb 13 2022 (didn't change original)
The getTime method returns the number of milliseconds elapsed between 1st of January, 1970 00:00:00 and the given date.
Date
object, so we don't mutate it in place when calling the setDate
method.Copying the date is quite useful when you have to use the original Date
object
in other places in your code.