JS实现闰年判断及指定年月天数计算的代码咨询
JavaScript 闰年判断与月份天数计算实现
1. 闰年判断函数
判断规则遵循公历标准:
- 普通闰年:年份是4的倍数,且不是100的倍数
- 世纪闰年:年份是整百数时,必须是400的倍数
function isLeapYear(year) { // 输入合法性校验 if (typeof year !== 'number' || !Number.isInteger(year) || year < 1) { throw new Error('请输入合法的正整数年份'); } return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0); }
2. 计算指定年月的天数
逻辑说明:
- 1、3、5、7、8、10、12月固定为31天
- 4、6、9、11月固定为30天
- 2月调用闰年判断函数,返回29天(闰年)或28天(平年)
function getMonthDays(year, month) { // 输入合法性校验,默认月份取值为1-12 if (typeof month !== 'number' || !Number.isInteger(month) || month < 1 || month > 12) { throw new Error('请输入1-12之间的合法月份'); } const bigMonths = [1,3,5,7,8,10,12]; if (bigMonths.includes(month)) return 31; if ([4,6,9,11].includes(month)) return 30; // 2月单独处理 return isLeapYear(year) ? 29 : 28; }
提示:如果你的项目中月份取值为JS Date默认的0-11范围,可自行修改
getMonthDays函数的输入校验规则和月份匹配逻辑即可。
3. 使用示例
// 测试闰年判断 console.log(isLeapYear(2020)); // 输出 true console.log(isLeapYear(2023)); // 输出 false console.log(isLeapYear(2000)); // 输出 true console.log(isLeapYear(1900)); // 输出 false // 测试月份天数计算 console.log(getMonthDays(2020, 2)); // 输出 29 console.log(getMonthDays(2023, 2)); // 输出 28 console.log(getMonthDays(2024, 4)); // 输出 30 console.log(getMonthDays(2024, 8)); // 输出 31
内容的提问来源于stack exchange,提问作者Satine Agababyan
相关产品推荐
相关产品推荐

