根据当前时间动态获取上一个月的时间及获取当月的最后一天

业务需求中,经常会根据当前时间获取上一个月的时间或者当月的最后一天,由于每个月的天数都不同,为了考虑时间上的准确性我们需要做一些判断和计算,具体方法如下:

/* 获取上一个月时间,返回yyyy-MM-dd字符串
* getLastMonthTime('2020-04-16','date'); date类型
* getLastMonthTime(new Date,'num'); //时间戳类型
* */
function getLastMonthTime(date, type){
    var daysInMonth = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    if(type == 'date'){ //时间戳格式
        date = new Date(date);
    }
    var strYear = date.getFullYear();
    var strDay = date.getDate();
    var strMonth = date.getMonth()+1;
    //判断二月份天数
    if (((strYear % 4) === 0) && ((strYear % 100)!==0) || ((strYear % 400)===0)){
        daysInMonth[2] = 29;
    }
    //判断跨年
    if(strMonth - 1 === 0){
        strYear -= 1;
        strMonth = 12;
    }else{
        strMonth -= 1;
    }
    strDay = Math.min(strDay,daysInMonth[strMonth]);
    strMonth = strMonth<10?"0"+strMonth:strMonth;
    strDay = strDay<10?"0"+strDay:strDay;
    return strYear+"-"+strMonth+"-"+strDay;
}

/* 获取每月的最后一天
 * date类型为(yyyy-MM-dd HH:mm:ss、yyyy-MM-dd HH:mm、yyyy-MM-dd HH、yyyy-MM-dd 、yyyy-MM)
 *  */
function getLastDay(date) {
    var dateMonth  = date.substr(5,2);
    var month = ['01','02','03','04','05','06','07','08','09','10','11','12'];
    var daysInMonth = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    var fullYear = new Date(date).getFullYear();
    //判断二月份天数
    if (fullYear % 4 == 0 && (fullYear % 100 != 0 || fullYear % 400 == 0)){
        daysInMonth[1] = 29;
    }
    var lastDay = daysInMonth[month.indexOf(dateMonth)];
    return lastDay;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值