填写开始日期后根据天数或者月数计算结束日期

根据天数计算结束日期

const getEndDateForDays = (date,day) => {
    var newTime = Date.parse(date) //将日期时间转换为毫秒值
    var newTimes = newTime + 3600000 * 24 * (day - 1); //(day-1)天后的毫秒值,3600000 为1小时的毫秒值
    var newDate = moment(new Date(newTimes)).format("YYYY-MM-DD"); //将获取的毫秒值转换为对应的日期时间
    return newDate
}

根据月数计算结束日期

//根据月数计算结束日期
const getEndDateForMonth = (date, num) => {
    if (!date || !num) return;
    var num1 = parseInt(num);
    var d = new Date(date);

    var thisMonth = d.getMonth() + 1;
    var thisYear = d.getFullYear();
    var thisDay = d.getDate();
    var dateStr = "";
    var addCount = thisMonth + num1;
    var diffMonthCount = parseInt(addCount / 12); //取整

    if ((thisMonth + num1) === 12 * diffMonthCount) { //如果是本年
        if ((thisMonth + num1) === 12) {
            diffMonthCount = 0;
        } else {
            diffMonthCount = diffMonthCount - 1;
        }
    }
    if (thisMonth + num1 > 12) { //如果是大于一年
        thisYear += diffMonthCount;
    }
    thisMonth = (addCount) - 12 * diffMonthCount;
    if (thisMonth < 10) {
        thisMonth = "0" + thisMonth;
    }

    var thatDate = new Date(thisYear, thisMonth, 0); //当天数为0 js自动处理为上一月的最后一天
    var thatDay = thatDate.getDate(); //指定年月的当月最大天数
    let m1 = date.substring(5, 7);
    if (thisDay === 30 || thisDay === 31 || (m1 === "02" && thisDay >= 28)) {
        thisDay = thatDay;
        if (date) {
            let m2 = date.substring(5, 10);
            //  成立日为2月份,且期限为整年的判断闰年
            if (m2 === "02-28" && num % 12 === 0) {
                if (!(thisYear % (thisYear % 100 ? 4 : 400))) {
                    thisDay = "29";
                }
            }
        }
        dateStr = thisYear + "-" + thisMonth + "-" + thisDay;
    } else {
        dateStr = addMonth(date, num);
    }
    return dateStr;
}

const addMonth = (dtstr, n) => {
    let s = dtstr.split("-");
    let yy = parseInt(s[0]);
    let mm = parseInt(s[1]); 
    let dd = parseInt(s[2]); 
    var num= mm + parseInt(n);
   
    if(num/12 > 1){
      yy += Math.floor(num/12) 
      mm = num % 12
    }else{
      mm += parseInt(n);
    }
   
    //获取当前日期中月的天数
    let newDate = new Date(yy,mm,0)
    //这里传入的0代表获取上一个月的最后一天;如果传1,则获得当月的第一天
    let days = newDate.getDate()
    //天数大于当前月
    if(dd > days){
      dd = days
    }
   
    return yy + "-" + mm  + "-" + dd
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值