0

I'm trying to use the Javascript Date object to calculate a date in the future (3 months from today). I am however getting unexpected results, specifically, when adding 3 months, the output date is 2025 (for time travelers, it's 2018 this year)!

Doing a simple console.log returns some unexpected results as below:

var d = new Date();
console.log("Locale Time:"+ d.toLocaleDateString());
console.log("Month: "+d.getMonth());
d.setMonth(d.getMonth() + 3);
console.log("3 months from now: "+d.toLocaleDateString());

Returns:
// Note todays real date is 9 October 2018

Locale Time:10/9/2018 // This is correct
app.min.js:1 Month: 9 // No, the month is 10 (October)
app.min.js:1 3 months from now: 11/9/2025 // What? 

What am I doing wrong?

mauzilla
  • 3,574
  • 10
  • 50
  • 86

1 Answers1

0

The argument monthIndex is 0-based. This means that January = 0 and December = 11. so your code can be like this :

var d = new Date();
console.log("Locale Time:"+ d.toLocaleDateString());
console.log("Month: "+d.getMonth());
d.setMonth(d.getMonth() + 4);
console.log("3 months from now: "+d.toLocaleDateString());

Output will be

> "Locale Time:10/9/2018"
> "Month: 9" (October = 9 as monthIndex starts from 0)
> "3 months from now: 2/9/2019"