js 日期按年月日加减

<script>
function isleapyear(year)
{
if(parseInt(year)%4==0 && parseInt(year)%100!=0)return true;
if(parseInt(year)%400==0)return true;
return false;
} function datedrift(date,difference)
{
if(date.constructor!==Date)return Date();
var year=parseInt(date.getUTCFullYear()),
mon=parseInt(date.getUTCMonth())+1,
day=parseInt(date.getUTCDate());
if(typeof difference!="string" || difference.length==0)return date;
var units=difference.match(/([+-]\d{1,3}[myd])/ig);
for(var i=0;i<units.length;i++)
{
if(units[i].charAt(0)=='+')
{
var mark=units[i].substr(-1,1);
var value=parseInt(units[i].substr(1,units[i].length-2));
if(mark =='y')
{
year=year+value;
if(day==29)
{
year=year+value;
if(mon==2)
{
if(!isleapyear(year))
day=28;
}
}
}
else if(mark == 'm')
{
year+=Math.floor((value+mon-1)/12);
mon=(value+mon-1)%12+1;
if(day==29 && mon==2 && !isleapyear(year))day=28;
else if(day>=30 && mon==2)
{
if(isleapyear(year))day=29;
else day=28;
}
else if(day==31 && (mon==4 || mon==6 || mon==9 || mon==11))day=30;
}
else if(mark== 'd')
{
var tmp=new Date();
tmp.setTime(Date.parse(year+'-'+mon+'-'+day)+value*24*36e5);
year=tmp.getUTCFullYear();
mon=tmp.getUTCMonth()+1;
day=tmp.getUTCDate();
} }
else
{
var mark=units[i].substr(-1,1);
var value=parseInt(units[i].substr(1,units[i].length-2));
switch(mark)
{
case "y":
year-=value;
if(day==29)
{
if(mon==2)
{
if(!isleapyear(year))
day=28;
}
}
break;
case "m":
var minusyear=Math.floor(value/12);
if(value%12>0)
{
year=year-minusyear-1;
year+=Math.floor((mon+11-value%12)/12);
mon=(mon+11-(value%12))%12+1; if(day==29 && mon==2 && !isleapyear(year))day=28;
else if(day>=30 && mon==2)
{
if(isleapyear(year))day=29;
else day=28;
}
else if(day==31 && (mon==4 || mon==6 || mon==9 || mon==11))day=30;
}
else
{
year=year-minusyear;
if(day==29 && mon==2 && !isleapyear(year))day=28;
else if(day>=30 && mon==2)
{
if(isleapyear(year))day=29;
else day=28;
}
else if(day==31 && (mon==4 || mon==6 || mon==9 || mon==11))day=30;
}
break;
case "d":
var tmp=new Date();
tmp.setTime(Date.parse(year+'-'+mon+'-'+day)-value*24*36e5);
year=tmp.getUTCFullYear();
mon=tmp.getUTCMonth()+1;
day=tmp.getUTCDate();
break;
}
}
}
alert([year,mon,day]);
}
var curdate=new Date();
datedrift(curdate,"+5m -5m");
</script>
上一篇:springMVC框架返回JSON到前端日期格式化


下一篇:MYSQL日期类型的加减更新使用INTERVAL 1 DAY