从 JS Date 对象获取错误的天数

Moh*_*med 0 javascript

这可能真的很简单,我在某处错过了一些东西,但我需要找出一个月中有多少天,我遇到的一个问题是当我运行以下代码时,我没有得到正确的天数

Septemper(应该是 30 但得到 31 ):

const date = new Date("2021/9/11");
const daysInMonth = new Date(date.getFullYear(), date.getMonth(), 0).getDate();
console.log(date)
console.log(daysInMonth)
Run Code Online (Sandbox Code Playgroud)

八月(应该是 31 并且确实得到了 31)

const date = new Date("2021/8/11");
const daysInMonth = new Date(date.getFullYear(), date.getMonth(), 0).getDate();
console.log(date)
console.log(daysInMonth)
Run Code Online (Sandbox Code Playgroud)

十月(应该是 31 但得到 30)

const date = new Date("2021/10/11");
const daysInMonth = new Date(date.getFullYear(), date.getMonth(), 0).getDate();
console.log(date)
console.log(daysInMonth)
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我没有从他们那里得到预期的答案,所以我认为月份是从 0 开始计算的,但因为我提供了一个无关紧要的字符串。我希望你能帮我解决这个问题!

van*_*owm 6

date.getMonth() 返回从零开始的月份数,其中一月为 0,十二月为 11

所以你需要使用 date.getMonth() + 1