JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to add 1 day to date in JavaScript?

To add 1 day to date, follow the following steps:

  1. First, get the day of the month for the given Date object by calling the getDate() method.
  2. Add 1 to the day that you have obtained in step 1 and pass the resulting value to the setDate() method.

In this way, you can add 1 day to a date.

let d = new Date();
console.log(d); //Sun Feb 20 2022 00:41:19 GMT+0000 (Greenwich Mean Time)

d.setDate(d.getDate() + 1);
console.log(d); //Mon Feb 21 2022 00:41:19 GMT+0000 (Greenwich Mean Time)

JavaScript provides the Date class to represent date and time. You create a Date object by calling the Date() constructor.

The getDate() method returns an integer value between 1 and 31. This integer value is the day of the month that is represented by the Date object.

The setDate() method sets the day of the month, and it accepts an integer value.

It is important to note that if a date is the last day of the month or year, then adding a day will automatically increment the month and year.

let d1 = new Date('2021-01-31');
d1.setDate(d1.getDate() + 1);
console.log(d1); //Mon Feb 01 2021 00:00:00 GMT+0000 (Greenwich Mean Time)

let d2 = new Date('2019-12-31');
d2.setDate(d2.getDate() + 1);
console.log(d2); //Wed Jan 01 2020 00:00:00 GMT+0000 (Greenwich Mean Time)

In this example, we created a Date object representing 31st January, and adding 1 day gives 1st February.

Another Date object is created that represents 31st December 2019, and incrementing the date by 1 day gives 1st January 2020.

Recommended Posts