javaScript 計算兩個日期的天數相差

來源:互聯網
上載者:User

標籤:格式   code   meta   oda   time   math   strong   gettime   ida   

一:計算兩個日期相差的天數

1
<html> 2 <head> 3 <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> 4 <title></title> 5 </head> 6 7 <body> 8 <button onClick="btnCount_Click()">計算相差天數</button> 9 <script language="JavaScript"> 10 11 function btnCount_Click(){ 12 s1 = "2002-1-10" 13 s2 = "2002-10-1" 14 alert(DateDiff(s1,s2)) 15 } 16 17 //計算天數差的函數,通用 18 function DateDiff(sDate1, sDate2){ //sDate1和sDate2是2002-12-18格式 19 var aDate, oDate1, oDate2, iDays 20 aDate = sDate1.split("-") 21 oDate1 = new Date(aDate[1] + ‘-‘ + aDate[2] + ‘-‘ + aDate[0]) //轉換為12-18-2002格式 22 aDate = sDate2.split("-") 23 oDate2 = new Date(aDate[1] + ‘-‘ + aDate[2] + ‘-‘ + aDate[0]) 24 iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 /24) //把相差的毫秒數轉換為天數 25 return iDays 26 }

二:計算一定天數後的日期

 1 <script  language="javascript"  type="text/javascript">   2 var  startDate  =  new  Date  ();            3 var  intValue  =  0;   4 var  endDate  =  null;   5  6 intValue  =  startDate.getTime();            i 7 ntValue  +=  100  *  (24  *  3600  *  1000);   8 endDate  =  new  Date  (intValue);   9 alert  (endDate.getFullYear()+"-"+ (endDate.getMonth()+1)+"-"+ endDate.getDate());  10 </script> 

上面的100代表100天后的日期,你可以修改。JS中Date.getTime(),只能1970.01.01之後的日期;還有月份是0 - 11,有點不一樣,切忌哦。當然你也可以計算特定日期後的日期。

 1 <script  language="javascript"  type="text/javascript">   2 var  startDate  =  new  Date  (2007,  (8-1),  1,  10,  10,  10); 3 var  intValue  =  0;   4 var  endDate  =  null;   5  6 intValue  =  startDate.getTime();             7 intValue  +=  100  *  (24  *  3600  *  1000); 8 endDate  =  new  Date  (intValue);   9 alert  (endDate.getFullYear()+"-"+ (endDate.getMonth()+1)+"-"+ endDate.getDate());  10 </script>  

 

javaScript 計算兩個日期的天數相差

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.