时间:2021-07-01 10:21:17 帮助过:17人阅读
一、日期减去天数等于第二个日期
function cc(dd,dadd){ //可以加上错误处理 var a = new Date(dd) a = a.valueOf() a = a - dadd * 24 * 60 * 60 * 1000 a = new Date(a) alert(a.getFullYear() + "年" + (a.getMonth() + 1) + "月" + a.getDate() + "日") } cc("12/23/2002",2)
这里不得不做补充,浪费好多时间得出教训:
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>