gpt4 book ai didi

javascript - 一个月中给出奇怪结果的天数

转载 作者:太空宇宙 更新时间:2023-11-04 15:30:04 24 4
gpt4 key购买 nike

我创建了以下函数,该函数应返回一个月中的天数,但没有得到预期结果。

export const getNumberOfDaysInMonth = (year, month) => {

const myDate = new Date(year, month - 1, 0);
return myDate.getDate();
}

我正在传递年 = 2017月 = 6。正如您将看到的,我从月份中减去 1,因为据我了解,JS 使用基于 0 的月份计数系统。

这会将 myDate 设置为 2017 年 5 月 31 日,并且函数返回 31 天。

如果我将公式更改为 const myDate = new Date(year, Month - 1, 1);,它会将日期设置为 2017 年 6 月 1 日,并返回 1 天作为天。

我可以使用 switch 语句返回一个月中的天数,但这看起来很麻烦,而且它甚至不会考虑闰年等。有没有一种优雅的方法来获取一个月中的总天数特定年份的特定月份?

例如,如果我通过了year = 2016month = 2,我应该得到29而不是28。

最佳答案

做的时候

const myDate = new Date(year, month - 1, 0);

您不需要从月份中减去1。这是因为这里的日期函数中的第三个参数代表月份的day,被设置为0,这实际上意味着上个月的最后一天。所以就这样做

const myDate = new Date(year, month, 0);

应该为您提供所需的一个月中的天数结果。

关于javascript - 一个月中给出奇怪结果的天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44867057/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com