0

Current Date : 2019-10-14

I try like this :

var b = new Date()
var c = new Date(b.setMonth(b.getMonth() + 3));
c = c.toISOString().substr(0, 10)
console.log(c)

The result : 2020-01-14

But I want maximum date is last date on the third month. That is 2019-12-31

How can I do it?

Update

For example :

Current Date : 2019-11-03, then the result is 2020-01-31

Current Date : 2020-01-09, then the result is 2020-03-31

moses toh
  • 12,344
  • 71
  • 243
  • 443

2 Answers2

1

var b = new Date();
var c = new Date(b.getFullYear(), b.getMonth() + 3, 0);
console.log(c)
console.log(c.toISOString().substr(0, 10))
console.log(c.toLocaleDateString())
var b = new Date();
var c = new Date(b.getFullYear(), b.getMonth() + 3, 0);
console.log(c);
c = c.toISOString().substr(0, 10)
console.log(c);
Tue Dec 31 2019 00:00:00 GMT+0300 (GMT+03:00)
2019-12-31

Bilals "first" answer is actually correct. Its because toISOString and your time zone offset which you can fix with getTimezoneOffset() or use toLocaleDateString() method.

Erailea
  • 68
  • 3
  • 6
  • Be careful with *toISOString*. For users east of Greenwich, the above will show 1 day earlier than you expect. Run on 15 Oct 2019, a user in GMT+10 will get "2019-12-30T14:00:00.000Z", 2019-12-30, 31/12/2019. – RobG Oct 15 '19 at 03:28
  • Bilals answer is not a good one and will fail regularly. It doesn't add the months correctly, it doesn't set the date to the end of the month and the use of *toISOString* can offset the date by one day for some users. – RobG Oct 15 '19 at 03:39
0

You can pass 1 as third argument in date constructor:

var b = new Date()
b.setMonth(b.getMonth() + 3);
var c = new Date(b.getFullYear(), b.getMonth(), 1);
c = c.toISOString().substr(0, 10)
console.log(c)
Bilal Siddiqui
  • 3,579
  • 1
  • 13
  • 20