为什么在 Javascript 日期对象上使用 getDay() 方法和 getUTCDay() 方法无法获得相同的结果
Why I canot get the same result using the getDay() method and the getUTCDay() method on the Javascript Date object
今天是星期一 00:51 我来自魁北克市,因此我在 GMT-0500 (UTC−05:00)
我不知道为什么下面的代码会给我 2 个不同的结果:
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() 方法 returns 根据当地时间指定日期的星期几,其中 0 表示星期日。
和getUTCDay()方法说的完全一样returns根据世界时指定日期的星期几,其中0表示星期日。
唯一的区别是一个是根据当地时间,另一个是根据世界时...
我不确定我应该验证什么来理解我尝试过的区别 in Node.js (Typescript) and in the console 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')
创建的日期正好是 2019 年 2 月 18 日 UTC 时间 .
的午夜
如果您所在的时区具有负偏移量,那么该日期实际上是当地时间的星期日(魁北克市的时间为 GMT-0500,因此该日期为当地时间 2019-02-17:19:00:00 ).
因此,如果您所在的时区具有负偏移量,则 .getDay()
正确返回周日的 0
,而 .getUTCDay()
正确返回周一的 1
.
今天是星期一 00:51 我来自魁北克市,因此我在 GMT-0500 (UTC−05:00)
我不知道为什么下面的代码会给我 2 个不同的结果:
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() 方法 returns 根据当地时间指定日期的星期几,其中 0 表示星期日。
和getUTCDay()方法说的完全一样returns根据世界时指定日期的星期几,其中0表示星期日。
唯一的区别是一个是根据当地时间,另一个是根据世界时...
我不确定我应该验证什么来理解我尝试过的区别 in Node.js (Typescript) and in the console 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')
创建的日期正好是 2019 年 2 月 18 日 UTC 时间 .
如果您所在的时区具有负偏移量,那么该日期实际上是当地时间的星期日(魁北克市的时间为 GMT-0500,因此该日期为当地时间 2019-02-17:19:00:00 ).
因此,如果您所在的时区具有负偏移量,则 .getDay()
正确返回周日的 0
,而 .getUTCDay()
正确返回周一的 1
.