I feel like I am missing something here.
The Date.getDay() method is supposed to return a value from 0-6. 0 for Sunday and 6 for Saturday.
Now I have two dates, both are 'Sunday' which should return 0.
new Date('1990-11-11').getDay() // returns 6
new Date('2016-1-3').getDay() // returns 0
What is causing the discrepancy? I dare to question the validity of the .getDay()
method, but I can't figure out what is going on.
EDIT
> new Date('1990-11-11')
Sat Nov 10 1990 17:00:00 GMT-0700 (MST)
> new Date('2016-01-03')
Sat Jan 02 2016 17:00:00 GMT-0700 (MST)
> new Date('2016-1-3') // they say this format is wrong, but it returns the right date
Sun Jan 03 2016 00:00:00 GMT-0700 (MST)
I don't understand what is going on. January 3rd is Sunday and November 11th 1990 is Sunday. Why is it saying Saturday?
The getDay() method returns the day of the week for the specified date according to local time, where 0 represents Sunday.
The getDay() method returns the day of the week (0 to 6) of a date.
The one that is wrong is the one that returns Sunday, and that must be because the format is incorrect. 1990-11-11
is interpreted as 00:00:00
on midnight of the 11th, UTC, which is 5pm on Saturday the 10th in your time zone.
If you use getUTCDay()
, you should get 0
for both dates.
new Date('1990-11-11').getUTCDay() // returns 0
new Date('2016-01-03').getUTCDay() // returns 0
Certainly, your claim that 1990-11-11
is Sunday is true but you have to understand that JavaScript Date
object:
Your own tests illustrate this:
new Date('1990-11-11').getDay() // returns 6
> new Date('1990-11-11')
Sat Nov 10 1990 17:00:00 GMT-0700 (MST)
What happens is that constructor assumes local time or UTC depending on the syntax used:
Note: Where Date is called as a constructor with more than one argument, the specifed arguments represent local time. If UTC is desired, use new Date(Date.UTC(...)) with the same arguments.
Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.
... and your syntax makes it as UTC. But many others methods assume local time:
The getDay() method returns the day of the week for the specified date according to local time, where 0 represents Sunday.
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