Date.getDay()返回不同的值 [英] Date.getDay() is returning different values

查看:60
本文介绍了Date.getDay()返回不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得我在这里缺少什么.

I feel like I am missing something here.

Date.getDay()方法应该返回一个介于0到6之间的值.星期日为0,星期六为6.

The Date.getDay() method is supposed to return a value from 0-6. 0 for Sunday and 6 for Saturday.

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

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

是什么原因导致差异?我敢于质疑 .getDay()方法的有效性,但我不知道发生了什么.

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.

编辑

> 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日是星期日.为什么说星期六?

I don't understand what is going on. January 3rd is Sunday and November 11th 1990 is Sunday. Why is it saying Saturday?

推荐答案

当然,您声称 1990-11-11 是星期日是正确的,但是您必须了解JavaScript Date 对象:

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)

会发生什么情况,即构造函数假定本地时间或UTC取决于所使用的语法:

注意:其中Date作为具有多个以上构造函数的构造函数被调用自变量,指定的自变量表示本地时间.如果UTC是根据需要,使用带有相同参数的新Date(Date.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.

注意:使用Date构造函数解析日期字符串(和强烈建议不要使用Date.parse,它们等效)浏览器的差异和不一致之处.支持RFC 2822格式字符串仅按惯例.对ISO 8601格式的支持在以下方面有所不同仅日期的字符串(例如"1970-01-01")被视为UTC,而不是本地的.

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.但是许多其他方法假定是本地方法时间:

... and your syntax makes it as UTC. But many others methods assume local time:

getDay()方法返回指定日期的星期几根据当地时间,其中0代表星期日.

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

这篇关于Date.getDay()返回不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆