关于javascript:Date.getDay()返回不同的值

Date.getDay() is returning different values

本问题已经有最佳答案,请猛点这里访问。

我觉得我错过了一些东西。

getday()方法应该返回0-6之间的值。星期日为0,星期六为6。

现在我有两个约会,都是"星期日",应该返回0。

1
2
new Date('1990-11-11').getDay() // returns 6
new Date('2016-1-3').getDay() // returns 0

是什么导致了这种差异?我敢质疑.getDay()方法的有效性,但我不知道到底发生了什么。

编辑

1
2
3
4
5
6
> 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)

我不明白发生了什么事。1月3日为星期日,1990年11月11日为星期日。为什么说星期六?


错误的那个是返回星期日的那个,这一定是因为格式不正确。1990-11-11被解释为00:00:00,时间是11日午夜,UTC,也就是周六下午5点,也就是您所在时区的第10天。

如果您使用getUTCDay(),那么两个日期都应该使用0

1
2
new Date('1990-11-11').getUTCDay() // returns 0
new Date('2016-01-03').getUTCDay() // returns 0


当然,您声称1990-11-11是星期天的说法是正确的,但您必须理解javascript Date对象:

  • 处理时间和日期
  • 时区知道吗
  • 设计不好,相当违反直觉

您自己的测试说明了这一点:

1
2
3
new Date('1990-11-11').getDay() // returns 6
> new Date('1990-11-11')
Sat Nov 10 1990 17:00:00 GMT-0700 (MST)

根据所使用的语法,构造函数假定为本地时间或UTC:

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.

…您的语法使它成为UTC。但其他许多方法都假定当地时间:

The getDay() method returns the day of the week for the specified date
according to local time, where 0 represents Sunday.


getday返回日索引(从0到6),其中0是星期日。https://developer.mozilla.org/en/docs/web/javascript/reference/global_objects/date/getday

返回值:根据当地时间,给定日期对应星期几的整数:0表示星期日,1表示星期一,2表示星期二,依此类推。

更新:新日期构造函数为这些日期返回不同的时间值。

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

江户十一〔一〕号

出于某种原因,第一个在你的机器上被解释为星期六。很抱歉不能帮上更多的忙

更新2:

月/日使用两位数应使结果标准化。例子:

埃多克斯1〔2〕

getDay