获取某个月的天数,这个题个别都是在学 switch(){}
一章的案例。
咱们始终解题的计划是依据一个顺口溜:一三五七八十腊,31天永不差,四六九十一,每月30天,惟有二月二十八,平年要把日加一。(我搜的,具体怎么背我忘了)
这外面还有个平年的计算规定:四年一闰,百年不闰,四百年再闰。能够被4整除,然而不能被100整除,除非能够被400整除。
是不是被下面的魔性概念驯服了?接来下咱们来实现一下
面试题:JS 获取某月的天数
先上测试用例
function getMonthCountDay(year, month){ // year 为年份,month 为月份}[[2000,2],[2000,1],[2000,3],[2000,4],[2100,2],[2100,1],[2100,3],[2100,4],[2104,2],[2104,1],[2104,3],[2104,4],[2105,2],[2105,1],[2105,3],[2105,4],].map(v=>`${v} => ${getMonthCountDay.apply(null,v)}天`)
根底版本
依据咱们的顺口溜咱们来写一下
function getMonthCountDay (year, month) { switch (month){ case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31 case 4: case 6: case 9: case 11: return 30 case 2: return year%400==0?(29):(year%4!=0||year%100==0?28:29) }}
很好写完了,除了代码看上去多了点,没别的故障。
测试截图
借助 Date
API 解决日期溢出个性(进位)
接下来就开始骚了。
function getMonthCountDay (year, month) { return 32 - new Date(year, month-1, 32).getDate()}
是不是想不到,这种办法写的一下就很少了。
测试截图
计划原理
js 中 Date 在解决工夫的时候会做进位退位操作。
借助 Date
API 解决日期溢出个性(退位计划)
方才是用的进位,而后减去多余的。当初咱们改用退位
function getMonthCountDay (year, month) { return new Date(year, month, 0).getDate()}
测试截图
计划原理
js 中 Date 在解决工夫的时候会做进位退位操作。