Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
93
rated 0 times [  96] [ 3]  / answers: 1 / hits: 15792  / 10 Years ago, tue, september 9, 2014, 12:00:00

I am trying to convert a string to a Date object, and it works for all days except for December 31st where by object says December 1st instead of 31st. I have no idea why. Here is my JavaScript code:



var dt = new Date();
dt.setDate(31);
dt.setMonth(11);
dt.setFullYear(2014);


but my variable value is:



Mon Dec 01 2014 11:48:08 GMT+0100 (Paris, Madrid)


If I do the same for any other date, my object returns to the appropriate value. Do you have any idea what I did wrong?


More From » date

 Answers
26

setMonth should before setDate: (not safe for Months less than 31 days)



var dt = new Date();
dt.setFullYear(2014);
dt.setMonth(11);
dt.setDate(31);


And setMonth's second parameter also could be used to set date.



var dt = new Date();
dt.setFullYear(2014);
dt.setMonth(11, 31);




If no arguments are provided for the constructor, it will use the current date and time according to system settings.



So, using setMonth and setDate separately would still cause unexpected result.



If the values set are greater than their logical range, the value will be auto adjusted to the adjacent value.



For example, if today is 2014-09-30, then



var dt = new Date();
dt.setFullYear(2014); /* Sep 30 2014 */
dt.setMonth(1); /* Mar 02 2014, see, here the auto adjustment occurs! */
dt.setDate(28); /* Mar 28 2014 */


To avoid this, set the values using the constructor directly.



var dt = new Date(2014, 11, 31);

[#69521] Saturday, September 6, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harleyterryp

Total Points: 290
Total Questions: 92
Total Answers: 95

Location: Montenegro
Member since Sun, May 7, 2023
1 Year ago
;