How to add Days to a Date in TypeScript

avatar

Borislav Hadzhiev

Mon Mar 07 20222 min read

banner

Photo by Nathan Wolfe

Add Days to a Date in TypeScript #

To add 1 day to a date:

  1. Use the getDate() method to get the day of the month for the given date.
  2. Use the setDate() method to set the day of the month.
  3. The setDate method takes the day of the month as a parameter and sets the value for the date.
index.ts
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.

index.ts
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.

index.ts
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.

Note that the 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.
index.ts
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.

We used the timestamp to create a copy of the 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.

Use the search field on my Home Page to filter through my more than 1,000 articles.