Maulik Modi
Maulik Modi

Reputation: 1306

JavaScript setMonth() method issue

It seems this Date.setMonth function of JavaScript is doing something it is not intended for. Here is code snippet. We are trying to get last date of every month in this scenario.

var d = new Date(2018, 11, 31); // this would set it to Dec 31 2018
d.setMonth(d.getMonth() + 1);   // this would set it to Jan 31 2019
d.setMonth(d.getMonth() + 1);   // this would set it to March 03 2019
alert(d);

So here, it seems that set month function just added 30 days to previous date (31 Jan 2019) which is ambiguous. This same problem can happen in the case of month with 30 days.

Is there any workaround that can give us exact solution to this problem where adding months would just change months? and set the date to last date if not existing?

Upvotes: 0

Views: 853

Answers (3)

Devesh
Devesh

Reputation: 170

For February 2019 date of the month lies in between 1 to 28 but date is already set as 31, so it will set date 3 for the next month because 31-28=3. For reference check this.

To get the last date of the month, try this :

var d = new Date(2018, 11, 31);  // Dec 31 2018  
var last = new Date(d.getFullYear(), d.getMonth() + 2, 0);
console.log(last); // Jan 31 2019
last = new Date(d.getFullYear(), d.getMonth() + 3, 0);
console.log(last); // Feb 28 2019

Upvotes: 0

Giulio Bambini
Giulio Bambini

Reputation: 4755

Try

new Date(d.getFullYear(), d.getMonth() + 1);

var d = new Date();
var d = new Date(d.getFullYear(), d.getMonth() + 1);
console.log(d); // last day

Upvotes: 1

Salman Arshad
Salman Arshad

Reputation: 272006

To get the last date of next month use the following:

var d = new Date(2018, 11, 31); // Dec 31 2018
d.setDate(1);                   // first day of current month
d.setMonth(d.getMonth() + 2);   // add *two* months
d.setDate(0);                   // 0 makes the date roll back to previous month
d;                              // Jan 31 2019

Upvotes: 2

Related Questions