JS日期加减,日期运算代码
程序员文章站
2023-12-14 09:15:46
一、日期减去天数等于第二个日期function cc(dd,dadd){//可以加上错误处理var a = new date(dd)a = a.valueof()a = a - dadd * 24 *...
一、日期减去天数等于第二个日期
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>