Date.getDay() is returning different values

This question already has an answer here:

  • Why does Date.parse give incorrect results? 10 answers

  • Certainly, your claim that 1990-11-11 is Sunday is true but you have to understand that JavaScript Date object:

  • Handles time as well as date
  • Is time zone aware
  • Is poorly designed and rather counter-intuitive
  • 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 (eg "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.


    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
    

    getDay returns day index (from 0 to 6), where 0 is Sunday. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/getDay

    Return value: An integer number corresponding to the day of the week for the given date, according to local time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on.

    Update: new Date constructor returns different time values for those dates.

    new Date('2016-1-3') ==> Sun Jan 03 2016 00:00:00 GMT+0100 (CET)

    new Date('1990-11-11') ==> Sun Nov 11 1990 01:00:00 GMT+0100 (CET)

    And for some reason, the first one gets interpreted as Saturday on your machine. Sorry for not being able to help out more

    Update2:

    Using two digits for month/day should standardize the results. Example:

    (new Date('2016-01-03')).getDay() ==> 0

    链接地址: http://www.djcxy.com/p/18616.html

    上一篇: Javascript新日期()返回无效日期

    下一篇: Date.getDay()返回不同的值