How can I add the months of the current date in javascript? [duplicate]


Good I have this code

var d = new Date();
var strDate = d.getFullYear() + "-" + (d.getMonth()+4) + "-" + d.getDate();

but as it is the end of the year when adding up, it gives me 22-15-2018 when it should be 22-03-2019

How can I make it for him to bring it correctly?

asked by Juan Jose 22.12.2018 в 19:50

1 answer


We have at our disposal the method setMonth() to which we are going to do the increase of months that we want to add to the original or current date

setMonth() establishes a specific month according to the established year, which in our year is 2018 at the time of doing var e = new Date()

var e = new Date()
e.setMonth(e.getMonth() + 4)

console.log("fecha: "+e.getFullYear() +"-"+ (e.getMonth()+1) +"-"+ e.getDate())

The previous exercise will show us as the final date: "fecha: 2019-4-22" but why?

Well, because the months start at position 0, then if I leave only +4 I indicate that it will arrive until March, on the contrary if apart from that, inside my console.log, I do e.getMonth() + 1 then it starts in position 1, which in months would be Febrero , so it will show me the date in the month of Abril

That is to say, the months read them like this:

Posición    0   |    1    |   2     |   3   |   4
Mes       Dic   | Enero   | Febrero | Marzo | Abril
answered by 22.12.2018 / 20:27