Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add One Month to a Date in JavaScript

I have an input field that needs to be incremented by one month using the JavaScript Date object. Below is an example of an effort I have made in incrementing the month. The issue with this seems to be that it will display 0 as January and does not increment the year.

nDate.setDate(nDate.getDate());
inputBox1.value = (nDate.getMonth() + 1) + "/" + (nDate.getDate()) + "/" +  (nDate.getFullYear());
like image 751
leora Avatar asked May 17 '10 11:05

leora


People also ask

How do you add 1 month in moment?

To add 1 month from now to current date in moment. js and JavaScript, we can use the add method. const startDate = "20-03-2022"; const newDate = moment(startDate, "DD-MM-YYYY").

What is now () in JavaScript?

now() method is used to return the number of milliseconds elapsed since January 1, 1970, 00:00:00 UTC. Since now() is a static method of Date, it will always be used as Date.

What is getDate () in JavaScript?

getDate() The getDate() method returns the day of the month for the specified date according to local time.


1 Answers

Use Date.setMonth:

var d = new Date(2000, 0, 1); // January 1, 2000
d.setMonth(d.getMonth() + 1);
console.log(d.getFullYear(), d.getMonth() + 1, d.getDate());

Date.setMonth is range proof i.e. months other than 0...11 are adjusted automatically.

like image 196
Salman A Avatar answered Sep 23 '22 18:09

Salman A