且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JS日期、月份的加减

更新时间:2022-06-15 17:15:52

JS日期、月份的加减

需要注意的是返回的月份是从0开始计算的,也就是说返回的月份要比实际月份少一个月,因此要相应的加上1

// 日期,在原有日期基础上,增加days天数,默认增加1天
function addDate(date, days) {
if (days == undefined || days == '') {
days = 1;
}
var date = new Date(date);
date.setDate(date.getDate() + days);
var month = date.getMonth() + 1;
var day = date.getDate();
return date.getFullYear() + '-' + getFormatDate(month) + '-' + getFormatDate(day);
}

//月份,在原有的日期基础上,增加 months 月份,默认增加1月
function addMonth(date,months){
    if(months==undefined||months=='')
        months=1;
    var date=new Date(date);
    date.setMonth(date.getMonth()+months);
    var month=date.getMonth()+1;
    var day=date.getDate();
    return date.getFullYear()+'-'+getFormatDate2(month)+'-'+getFormatDate2(day);
}


// 日期月份/天的显示,如果是1位数,则在前面加上'0'
function getFormatDate(arg) {
if (arg == undefined || arg == '') {
return '';
}

var re = arg + '';
if (re.length < 2) {
re = '0' + re;
}
return re;
}