简体   繁体   English

JavaScript中星期几不正确

[英]Incorrect day of week in JavaScript

For the following date: 对于以下日期:

Wed Jan 06 2016 02:00:00 GMT+0200 (IST) 

The following expression (which is supposed to return the day of week of January 1) 以下表达式(应该返回1月1日的星期几)

new Date(date.getUTCFullYear(), 0).getUTCDay()

returns 4 instead of the expected 5 (it was Friday...) 返回4而不是预期的5(这是星期五...)

Why it doesn't work? 为什么不起作用?

I think that's because new Date is not in UTC anymore while getUTCDay is. 我认为这是因为getUTCDay new Date已不在UTC中。 Use getDay instead. 使用getDay代替。

$ new Date(2016, 0) $ new Date(2016,0)

Fri Jan 01 2016 00:00:00 GMT+0200 (EET) 2016年1月1日星期五00:00:00 GMT + 0200(EET)

notice the +0200 part. 注意+0200部分。

I hope this example will clarify your doubt 我希望这个例子可以澄清您的疑问

I am in IST time zone (GMT+0530) and depending upon the time of the day, either UTC is one day behind or the same day. 我处于IST时区(GMT + 0530),根据一天中的时间,UTC会晚一天或同一天。 Hence the result. 因此,结果。

var d1 = new Date(2016, 0, 6, 5, 29, 0); 
var d2 = new Date(2016, 0, 6, 5, 30, 0); 
console.log(d1.getUTCDay(), d2.getUTCDay()); //logs 2 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM