js获取当期日期累加天数
本文是转载的,,忘记出处了,我用上了,也给大家分享一下
一、日期减去天数等于第二个日期
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedBlock.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockEnd.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)
这里不得不做补充,浪费好多时间得出教训:
JavaScript 对时间的代号
0-11数字表示1-12月: var a= new Date(2006,5,6) 结果是2006-6-6
0-6表示星期
1-31表示日期
0-23小时
0-59分钟,秒
二。//两个日期的差值(d1 - d2).
function DateDiff(d1,d2){
var day = 24 * 60 * 60 *1000;
try{
var dateArr = d1.split("-");
var checkDate = new Date();
checkDate.setFullYear(dateArr[0], dateArr[1]-1, dateArr[2]);
var checkTime = checkDate.getTime();
var dateArr2 = d2.split("-");
var checkDate2 = new Date();
checkDate2.setFullYear(dateArr2[0], dateArr2[1]-1, dateArr2[2]);
var checkTime2 = checkDate2.getTime();
var cha = (checkTime - checkTime2)/day;
return cha;
}catch(e){
return false;
}
}//end fun
三、应用:
<script language="javascript" type="text/javascript">
var flag = Array();//全局变量
var start = "2009-01-01";
var end = "2009-02-24";
SetFlag(start,end);
for(var i=0; i<flag.length; i++){
document.write(flag[i]+"\n\r");
}
//设置周期内的日期(数组)
function SetFlag(start,end){
var cdate = Array();
cdate = start.split("-");
var cd = cdate[1]+"/"+cdate[2]+"/"+cdate[0];
var dayNum = DateDiff(end,start);
for(var i=0; i<=dayNum; i++){
flag.push(AddDays(cd,i));
}
}//end fun
//日期加上天数后的新日期.
function AddDays(date,days){
var nd = new Date(date);
nd = nd.valueOf();
nd = nd + days * 24 * 60 * 60 * 1000;
nd = new Date(nd);
//alert(nd.getFullYear() + "年" + (nd.getMonth() + 1) + "月" + nd.getDate() + "日");
var y = nd.getFullYear();
var m = nd.getMonth()+1;
var d = nd.getDate();
if(m <= 9) m = "0"+m;
if(d <= 9) d = "0"+d;
var cdate = y+"-"+m+"-"+d;
return cdate;
}
//两个日期的差值(d1 - d2).
function DateDiff(d1,d2){
var day = 24 * 60 * 60 *1000;
try{
var dateArr = d1.split("-");
var checkDate = new Date();
checkDate.setFullYear(dateArr[0], dateArr[1]-1, dateArr[2]);
var checkTime = checkDate.getTime();
var dateArr2 = d2.split("-");
var checkDate2 = new Date();
checkDate2.setFullYear(dateArr2[0], dateArr2[1]-1, dateArr2[2]);
var checkTime2 = checkDate2.getTime();
var cha = (checkTime - checkTime2)/day;
return cha;
}catch(e){
return false;
}
}//end fun
</script>