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

 

 

  

转载于:https://www.cnblogs.com/ajuan/p/10384932.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值