方法:1、使用“new Date(year, month,0)”語句根據指定年份和月份來創建日期對象;2、使用“日期對象.getDate()”語句處理日期對象,返回指定月份的最后一天,即可知道指定月份有多少天。

本教程操作環境:windows7系統、javascript1.8.5版、Dell G3電腦。
javascript根據月判定有多少天的方法
要想得到某月有多少天,只需要獲取到當月最后一天的日期就行了
方法1:
靈活調用 setMonth(),getMonth(),setDate(),getDate(),計算出所需日期
實現代碼:
function getMonthLength(date) { let d = new Date(date); // 將日期設置為下月一號 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:
原來還有更簡單的辦法:直接調用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)

【
站長資訊網