4

I have a piece of code to find the next month of the given date.

var d = new Date('2018-03-31');
dt = new Date(d.setMonth(d.getMonth() + 1));
document.getElementById("demo").innerHTML = dt;

But i'm wondering what is wrong here since it adds one month to March & gives May instead of April?

DEMO:

var d = new Date('2018-03-31');

dt = new Date(d.setMonth(d.getMonth() + 1));
document.getElementById("demo").innerHTML = dt;
<p id="demo"></p>
mpsbhat
  • 2,703
  • 10
  • 45
  • 103

4 Answers4

5

Use

setMonth(month, day)

d.setMonth(d.getMonth() + 1, 1); where day as 1st day of next month

Only if you are interested in Month part

var d = new Date('2018-03-31');

d.setMonth(d.getMonth() + 1, 1);

dt = new Date(d);
document.getElementById("demo").innerHTML = dt;
<p id="demo"></p>
Yogen Darji
  • 3,095
  • 15
  • 27
2

There's no 31st April so it goes to 1st May. You can try it with 2018-03-30

var d = new Date('2018-03-30');

dt = new Date(d.setMonth(d.getMonth() + 1));
document.getElementById("demo").innerHTML = dt;
<p id="demo"></p>
Thum Choon Tat
  • 2,866
  • 1
  • 20
  • 22
0

setMonth mutates the original Date object - try just setMonth and then referencing the date object again, rather than creating a new one:

var d = new Date('2018-03-31');
d.setMonth(d.getMonth() + 1);
document.getElementById("demo").innerHTML = d;
<p id="demo"></p>
CertainPerformance
  • 313,535
  • 40
  • 245
  • 254
-1

April only has 30 days. If you add 1 to month on the 31st of March, you'll be 1 month later, which is the 1st of May.

AdrianL
  • 9
  • 3