1. 概述
1.1 說明
在項目過程中,有時候需要默認展示一個月的查詢條件,即當月的第一天和最后一天。
2. 代碼
2.1 代碼示例
直接調用getFirstAndLastDay()即可得到當月的第一天和最后一天。
/** * 獲取當前月份的第一天和最后一天 **/ function getFirstAndLastDay() { let now = new Date(); let strLink = "-"; let year = now.getFullYear(); let month = now.getMonth() + 1; if (month >= 1 && month <= 9) { month = "0" + month; } let lastDay = this.getLastDay(year, month); let firstDate = year + strLink + month + strLink + '01'; let lastDate = year + strLink + month + strLink + lastDay; let returnArr = [firstDate, lastDate];//以數組形式返回 return returnArr; } /** * 獲取當月的最后一天 * @param year 年份 * @param month 月份 **/ function getLastDay(year,month){ let new_year = year; let new_month = month++;//取下一個月的第一天,方便計算(最后一天不固定) if(month>12){//如果當前大於12月,則年份轉到下一年 new_month -=12;//月份減 new_year++;//年份增 } // 取當年當月對應的下個月的前一天,即當前月的最后一天 let last_date = new Date(new_year,new_month,0).getDate(); return last_date; }