2

Date objects instantiated like this:

new Date("2011-12-13")

return a date object that consider themselves a Monday:

Date {Mon Dec 12 2011 16:00:00 GMT-0800 (PST)}

But according to my calendar, 12/13/2011 is a Tuesday. Oddly, when I instantiate the date object like this:

new Date("12/13/2011")

This (correctly) returns a Tuesday:

Date {Tue Dec 13 2011 00:00:00 GMT-0800 (PST)}

How can I use the syntax in my initial example (year-month-day) and also get the correct day of the week according to my calendar?

James
  • 5,273
  • 10
  • 51
  • 76

1 Answers1

7

You might want to check out https://stackoverflow.com/a/163584/436641 for some caveats on creating Date objects in JavaScript using strings. In a nutshell, for reliability, you should be doing this:

new Date(2011, 11, 13);

(Note that the second parameter, the month, is 0 for January through 11 for December, not 1 through 12.)

In your particular case, when you instantiate with "2011-12-13" it uses GMT and then adjusts to your local timezone, which in your case is eight hours behind GMT. So you are getting 4pm on the day before you are asking. So that's a Monday, not a Tuesday. (See in the result where it says the time is 16:00:00 and the date is the 12th rather than the 13th?)

When you instantiate with "12/13/2011", you get midnight on the 13th in your local timezone. So you get Tuesday, the day you requested.

The difference is (probably) explained by the fact that Date will pass the string to its static parse() method, which is (probably) treating one of those strings as an ISO 8601 timestamp and the other as an RFC 822 timestamp, and that the defaults/best-guesses for timezones for those timestamp formats are different. See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/parse for the situation with Firefox. Other browsers may or may not be the same. That's why it's best to not use strings (and if you do use strings, use long unambiguous standard timestamp formats rather than truncated ones).

Community
  • 1
  • 1
Trott
  • 66,479
  • 23
  • 173
  • 212
  • I added the probable reason as a last paragraph to my answer. Basically, `Date.parse()` has to guess what is intended when it gets a truncated timestamp string, so it's making a guess as to what it thinks is probably meant for the timezone. – Trott Dec 23 '11 at 06:03
  • It's worth noting that that if you add ` 00:00:00` to the string, you would get the results you're looking for. In my case, it's easier to just deal with the string and not parse out the date parts (and subtract 1 for the month). – John Fawcett Jan 23 '14 at 19:54