When creating a new Date
object using numbers for the parts, the value I get back is exactly one month ahead of the value I put in for 'month'.
new Date(2012, 05, 17, 00, 00, 00)
Sun Jun 17 2012 00:00:00 GMT+0800 (HKT) // june?!
However, a normal parse of exactly the same string returns the correct time:
new Date("2012-05-17 00:00:00")
Thu May 17 2012 00:00:00 GMT+0800 (HKT)
I get the same result in ie/ff/chrome. Removing hours/min/seconds doesn't have any effect. I can work around it by subtracting one before setting the month, but instead I just switched to writing out my date as a string.
Edit: The string parse doesn't work in IE. I have no idea what I did, but I swear I made that work. Thats prob. why I avoided it in the first place. I've switched to using moment.js for now.
Ah, now I get it. Just like regular java dates, which I don't code in except rarely, and even then always with a library (joda, etc). What a terrible idea anyway. Here is skeets take on the question: Why is January month 0 in Java Calendar?
Why is this happening?
By default, when you run new Date() in your terminal, it uses your browser's time zone and displays the date as a full text string, like Fri Jul 02 2021 12:44:45 GMT+0100 (British Summer Time).
Return value Calling the Date() function (without the new keyword) returns a string representation of the current date and time, exactly as new Date(). toString() does.
You can create a Date object using the Date() constructor of java. util. Date constructor as shown in the following example. The object created using this constructor represents the current time.
new Date() exhibits legacy undesirable, inconsistent behavior with two-digit year values; specifically, when a new Date() call is given a two-digit year value, that year value does not get treated as a literal year and used as-is but instead gets interpreted as a relative offset — in some cases as an offset from the ...
Programmers start counting from 0. So months are represented by 0(Jan)-11(Dec).
The reason days don't follow this rule is to not confuse authors with 30/31 month differences.
From MDN:
month
Integer value representing the month, beginning with 0 for January to 11 for December.
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