JavaScript 当月第一天和最后一天

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;
    }

 

 

  

posted @ 2019-02-15 17:39  ajuan  阅读(1329)  评论(0编辑  收藏  举报