日期:2014-05-16  浏览次数:20411 次

某个时间增加/减去N天之后的时间--JS方法
//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;
    }
}