由於每個月的天數並不固定,直接判斷會比較麻煩。一個巧妙的思路是:先求出「下一個月的第一天」,再減去一天,就能得到當月的最後一天。下面的函數實現了這個思路:
// 獲得某月的最後一天
function getLastDay(year, month) {
var new_year = year; // 當前年份
var new_month = month++; // 取下一個月的第一天,方便計算
if (month > 12) {
new_month -= 12; // 月份減
new_year++; // 年份增
}
var new_date = new Date(new_year, new_month, 1); // 當年當月的第一天
return (new Date(new_date.getTime() - 1000 * 60 * 60 * 24)).getDate(); // 前一天的日期即當月最後一天
}
獲取 2013 年 6 月最後一天的代碼:
2013年6月的最後一天是:<span id="last_keleyi_com"></span>
$("#last_keleyi_com").text(getLastDay(2013, 6))
獲取本月最後一天的代碼:
本月最後一天是:<span id="thislast_keleyi_com"></span>
var myDate = new Date();
$("#thislast_keleyi_com").text(getLastDay(myDate.getFullYear(), myDate.getMonth() + 1))
以上示例用到了 jQuery 框架來把結果寫入頁面。核心邏輯只有一句:用「下個月 1 號減一天」的方式巧妙避開了每月天數不一致的判斷問題。