Borislav Hadzhiev
Mon Mar 07 2022·2 min read
Photo by Nathan Wolfe
To add 1 day to a date:
getDate()
method to get the day of the month for the given date.setDate()
method to set the day of the month.setDate
method takes the day of the month as a parameter and sets the
value for the date.const date = new Date('2022-09-23'); // 👇️ add 1 day to Date date.setDate(date.getDate() + 1); // 👇️ Sat Sep 24 2022 console.log(date);
We used the
Date()
constructor to create a Date
object.
The
getDate()
method returns an integer between 1
and 31
that represents the day of the
month for the date.
The
setDate()
method takes a number that represents the day of the month as a parameter and
sets the value on the Date
.
If you do this often, you can create a reusable function that takes the number
of days and the Date
object as parameters.
function addDays(numOfDays: number, date = new Date()) { date.setDate(date.getDate() + numOfDays); return date; } const result1 = addDays(1, new Date('2022-09-23')); console.log(result1); // 👉️ Sat Sep 24 2022
The Date
object automatically takes care of rolling over the month and year
if adding X days to a date pushes us into the next month or year.
function addDays(numOfDays: number, date = new Date()) { date.setDate(date.getDate() + numOfDays); return date; } const result1 = addDays(7, new Date('2022-09-25')); console.log(result1); // 👉️ Sun Oct 02 2022
We added 7
days to the date, which pushed us into the next month and the
Date
object automatically took care of updating the month.
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 addDays(numOfDays: number, date = new Date()) { const dateCopy = new Date(date.getTime()); dateCopy.setDate(dateCopy.getDate() + numOfDays); return dateCopy; } const date = new Date('2022-09-25'); const result1 = addDays(3, date); console.log(result1); // 👉️ Wed Sep 28 console.log(date); // 👉️ Sun Sep 25 (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.
In general, mutating function arguments is a bad practice, as passing the same parameter to the same function multiple times returns different results.