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