欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

某个时间增加/减去N天之后的时间--JS方法

程序员文章站 2022-06-12 10:10:11
...
//date加上num天数之后等到的时间;date格式:YYYY-MM-DD
function dateAddNumDays(date,num)
{
var dates = date.split("-");
if(dates.length!=3)
{
alert("时间格式错误,请确认!");
return ;
}
var year = dates[0];
var month = dates[1];
var day = dates[2];
var newDay = Number(day)+Number(num);
var oldDay = newDay;
while(newDay>28){
if(month==1||month==3||month==5||month==7||month==8||month==10||month==12)
{
if(newDay>31)
{
month = Number(month)+1;
newDay = newDay-31;
}
}else if(month==4||month==6||month==9||month==11)
{
if(newDay>30)
{
month = Number(month)+1;
newDay = newDay-30;
}
}else{

if(isLeapYear(year)==true){
if(newDay>29)
{
month = Number(month)+1;
newDay = newDay-29;
}
}else{
if(newDay>28)
{
month = Number(month)+1;
newDay = newDay-28;
}
}

}
if(month>12)
{
month = month-12;
year = Number(year)+1;
}
if(oldDay == newDay)
{
break;
}
}
if(Number(month)<10)
{
month = "0"+Number(month);
}
if(newDay<10)
{
newDay = "0"+newDay;
}
return year+'-'+month+'-'+newDay;
}
//date减少num天数之后等到的时间;date格式:YYYY-MM-DD
function dateReduceNumDays(date,num)
{
var dates = date.split("-");
if(dates.length!=3)
{
alert("时间格式错误,请确认!");
return ;
}
var year = dates[0];
var month = dates[1];
var day = dates[2];
var newDay = Number(day)-Number(num);
while(newDay<=0)
{
if(month==1||month==2||month==4||month==6||month==8||month==9||month==11)
{
newDay = newDay+31;
month = Number(month)-1;

}else if(month==5||month==7||month==10||month==12)
{
newDay = newDay+30;
month = Number(month)-1;
}else{
if(isLeapYear(year)==true){
newDay = newDay+29;
}else{
newDay = newDay+28;
}
month = Number(month)-1;
}
if(month<=0)
{
month = month+12;
year = Number(year)-1;
}
}
if(Number(month)<10)
{
month = "0"+Number(month);
}
if(newDay<10)
{
newDay = "0"+newDay;
}
return year+'-'+month+'-'+newDay;
}
//判断是否是闰年
function isLeapYear(pYear){
if(!isNaN(pYear)){
if((pYear%4==0 && pYear%100!=0)||(pYear%100==0 && pYear%400==0)){
return true;
}else{
return false;
}
}else{
return false;
}
}
相关标签: function