简体   繁体   English

如果新日期(年、月、日),则获取日期工作错误

[英]Get day works wrong in case new Date(year, month, day)

I'm trying to get day of week by:我正在尝试通过以下方式获取星期几:

const date = new Date('2021/12/06')
date.getDay()

and it works properly, but when I create date by using new Date(2021, 12, 6) , it show me wrong number - 4 .它工作正常,但是当我使用new Date(2021, 12, 6)创建日期时,它显示错误的数字 - 4 Why is it happens, or I don't understand some exception for this way of creating date object?为什么会发生这种情况,或者我不明白这种创建日期 object 的方式有什么例外?

this is because month should be the month index (0 - 11) not the month order (1-12):这是因为月份应该是月份索引 (0 - 11) 而不是月份顺序 (1-12):

new Date(2021, 11, 6).getDay()

and not并不是

new Date(2021, 12, 6).getDay()

REF: Date() constructor: syntax REF: Date() 构造函数:语法

When you create a date by 3 params you have to use a month INDEX.当您通过 3 个参数创建日期时,您必须使用月份索引。 Starting by 0.从 0 开始。

So December is actually 11, not 12.所以 12 月实际上是 11 日,而不是 12 日。

If you use new Date(2021, 11, 6) you get the result you're looking for.如果你使用new Date(2021, 11, 6)你会得到你正在寻找的结果。

getDay() gets the index of the week. getDay() 获取一周的索引。 Sunday, Monday, Tuesday, etc. (0, 1, 2,3,...)星期日、星期一、星期二等 (0, 1, 2,3,...)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDay https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDay

I believe what you're looking for is getDate() https://www.w3schools.com/js/js_date_methods.asp我相信您正在寻找的是 getDate() https://www.w3schools.com/js/js_date_methods.asp

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

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