JavaScript 當月第一天和最後一天

1. 概述

1.1 說明

在項目過程當中,有時候須要默認展現一個月的查詢條件,即當月的第一天和最後一天。數組

 2. 代碼

2.1 代碼示例

  直接調用getFirstAndLastDay()便可獲得當月的第一天和最後一天。this

    /**
     * 獲取當前月份的第一天和最後一天
     **/
    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;
    }
相關文章
相關標籤/搜索