今天是星期一,上午 00:51 我来自魁北克市,因此我的时间为 GMT-0500 (UTC−05:00)
我不知道为什么下面的代码给了我两个不同的结果:
const weekday = Array('sunday', 'monday', 'tuesday', 'wednesday',
'thursday', 'friday', 'saturday');
console.log('getDay() =', weekday[new Date('2019-02-18').getDay()]);
// getDay() = sunday
console.log('getUTCDay() =', weekday[new Date('2019-02-18').getUTCDay()]);
// getUTCDay() = monday
在 MDN 网站上,他们说 getDay() 方法根据本地时间返回指定日期的星期几,其中 0 代表星期日。
他们说的完全一样 getUTCDay() 方法根据世界时间返回指定日期中的星期几,其中 0 代表星期日。
唯一的区别是一个是根据本地时间,另一个是根据世界时间...
我不确定我应该验证什么来理解我尝试过的差异 in Node.js (Typescript)并在控制台 Chrome DevTools (Javascript)
在我的计算机设置中,一周的第一天是星期日...
最佳答案
new Date(
string
)
使用 Date.parse()
来解析日期。
来自Date.parse()
docs :
When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time.
因此,new Date('2019-02-18')
创建的日期将恰好是 UTC 时间 2019 年 2 月 18 日午夜。
如果您所在的时区偏移量为负,则该日期实际上是本地时间星期日(魁北克市的时间为 GMT-0500,因此该日期为本地时间 2019-02-17:19:00:00)。
因此,如果您所在的时区偏移量为负,则 .getDay()
会正确返回周日的 0
,而 .getUTCDay()
周一正确返回 1
。
关于javascript - 为什么我无法在 Javascript Date 对象上使用 getDay() 方法和 getUTCDay() 方法获得相同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54741141/