方法:1、使用“new Date(year, month,0)”語(yǔ)句根據(jù)指定年份和月份來(lái)創(chuàng)建日期對(duì)象;2、使用“日期對(duì)象.getDate()”語(yǔ)句處理日期對(duì)象,返回指定月份的最后一天,即可知道指定月份有多少天。
本教程操作環(huán)境:windows7系統(tǒng)、javascript1.8.5版、Dell G3電腦。
javascript根據(jù)月判定有多少天的方法
要想得到某月有多少天,只需要獲取到當(dāng)月最后一天的日期就行了
方法1:
靈活調(diào)用 setMonth(),getMonth(),setDate(),getDate(),計(jì)算出所需日期
實(shí)現(xiàn)代碼:
function getMonthLength(date) { let d = new Date(date); // 將日期設(shè)置為下月一號(hào) d.setMonth(d.getMonth()+1); d.setDate('1'); // 獲取本月最后一天 d.setDate(d.getDate()-1); return d.getDate(); }
檢測(cè)一下:
getMonthLength("2020-02-1") getMonthLength("2021-02-1") getMonthLength("2022-02-1") getMonthLength("2022-03-1")
方法2:
原來(lái)還有更簡(jiǎn)單的辦法:直接調(diào)用getDate()
function getMonthLength(year,month,day) { return new Date(year, month,0).getDate(); }
檢測(cè)一下:
getMonthLength(2020,02,0) getMonthLength(2021,02,0) getMonthLength(2022,02,0) getMonthLength(2022,03,0) getMonthLength(2022,04,0)
【