根据当前日期回显几个月之前的日期(快速获取时间段)

// 快速选择日期回显
$(function(){
    var date=new Date();
    var year=date.getFullYear();
    var month=date.getMonth()+1>=10?date.getMonth()+1:'0'+(date.getMonth()+1);
    var day=date.getDate()>=10?date.getDate():'0'+date.getDate();
    var nowdatestr=year+"-"+month+"-"+day;
    $("#endtime").val(nowdatestr);
    $("#starttime").val(getPreMonthDay(nowdatestr,3));
});
$("#dateNum").change(function() {
    var val = $("#dateNum").val();
    var date=new Date();
    var year=date.getFullYear();
    var month=date.getMonth()+1>=10?date.getMonth()+1:'0'+(date.getMonth()+1);
    var day=date.getDate()>=10?date.getDate():'0'+date.getDate();
    var nowdatestr=year+"-"+month+"-"+day;
    $("#endtime").val(nowdatestr);
    $("#starttime").val(getPreMonthDay(nowdatestr,val));
});
//获取当前日期前N个月的日期
function getPreMonthDay(date,monthNum) {
    var dateArr = date.split('-');
    var year = dateArr[0]; //获取当前日期的年份
    var month = dateArr[1]; //获取当前日期的月份
    var day = dateArr[2]; //获取当前日期的日
    var days = new Date(year, month, 0);
    days = days.getDate(); //获取当前日期中月的天数
    var year2 = year;
    var month2 = parseInt(month) - monthNum;
    if (month2 <=0) {
        month2 = Math.abs(month2);
        var Pm = month2/12;
        var mm = Pm == 0 ? 1 : Math.ceil((month2) / 11);
        mm = parseInt(mm);
        year2 = parseInt(year2) - mm;
        month2 = 12 - (Math.abs(month2) % 12);
    }
    var day2 = day;
    var days2 = new Date(year2, month2, 0);
    days2 = days2.getDate();
    if (day2 > days2) {
        day2 = days2;
    }
    if (month2 < 10) {
        month2 = '0' + month2;
    }
    var t2 = year2 + '-' + month2 + '-' + day2;
    return t2;
}

posted @ 2019-08-16 15:26  砂糖一椰子  阅读(686)  评论(0编辑  收藏  举报