Date.Setmonth' Causes the Month to Be Set Too High If 'Date' Is at the End of the Month

`date.setMonth` causes the month to be set too high if `date` is at the end of the month

Let's break this down:

var d = new Date(); // date is now 2013-01-31
d.setMonth(1); // date is now 2013-02-31, which is 3 days past 2013-02-28
x = d.getMonth(); // what to do, what to do, 3 days past 2013-02-28 is in March
// so, expect x to be March, which is 2

This is only an issue when the day value of d is greater than the maximum number of days in the month passed to setMonth(). Otherwise, it works as you'd expect.

Why javascript set month gonna wrong month?

When the current date is 08-31, it is not entirely clear what is should mean to set the month to 9 because 09-31 is an invalid date.
That's why at some time someone had to define what setMonth should do in such situations. It seems that the defined behavior differs from the one you expect (you expected the date to become 09-30).

MDN (for setMonth) has some information about this:

The current day of month will have an impact on the behaviour of this method. Conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to return the new date.

It also refers to the actual specification which gives the exact algorithm which is used to calculate the result.
The reasons for the specification being as it is now are manifold, usually simplicity of the algorithm as well as the behavior on non-edge-cases are important factors.

Extract wrong Month from Date

The getMonth() method returns the month in the specified date
according to local time, as a zero-based value (where zero indicates
the first month of the year).

The value returned by getMonth is an integer between 0 and 11. 0
corresponds to January, 1 to February, and so on.

Javascript date string picking up incorrect month

DATE_OBJECT.getMonth() is zero based. (0 for January and 11 for December).

You need to do var y = x.getMonth() + 1;

See documentation: http://www.w3schools.com/jsref/jsref_getmonth.asp

Confuse about setUTC in Javascript

To answer your question, you are starting from the date Oct. 31. If you then set the month to 5, then this is equivalent to trying to change the date to June 31. Since no such date exists, it adjusts to July 1.

But if you want to create a Date object for June 1, 2016, then just create one:

var d  = new Date(2016, 5, 1);           // June 1, 2016, 12AM local time
var d2 = new Date(Date.UTC(2016, 5, 1)); // June 1, 2016, 12AM UTC

setMonth(1) gives me March?

Today is the 31st of January. When you d.setMonth(1); you are trying to set the date to the 31st of February. Since this date doesn't exist, it falls over to the 3rd of March.

Set the whole date when you initialise the object, don't try to change it piecemeal.



Related Topics



Leave a reply



Submit