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?
"The expression new Date() returns the current time in internal format, as an object containing the number of milliseconds elapsed since the start of 1970 in UTC.
The Date object is an inbuilt datatype of JavaScript language. It is used to work with dates and times. The Date object is created by using new keyword, i.e. new Date(). The Date object can be used date and time in terms of millisecond precision within 100 million days before or after 1/1/1970.
const date = new Date(); date. setDate(date. getDate() + 1); // ✅ 1 Day added console.
The date and time is broken up and printed in a way that we can understand as humans. JavaScript, however, understands the date based on a timestamp derived from Unix time, which is a value consisting of the number of milliseconds that have passed since midnight on January 1st, 1970.
The thing is, when you set a day first, you're still in the current month, so September. September has only 30 days so:
var dt = new Date(); /* today */ dt.setDate("31"); /* 1st Oct 2014 as should be by spec */ dt.setMonth("11"); /* 1st Dec 2014 */ dt.setFullYear("2014"); /* 1st Dec 2014 */
: (not safe for Months less than 31 days)setMonth
should before setDate
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With