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


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

比如:  
 str1  =  "2002-01-20"  
 str2  =  "2002-10-11"  
怎樣用javaScript計算出str1與str2之間相差的天數?  
---------------------------------------------------------------  
 
<html>  
<head>  
<meta  http-equiv="Content-Type"  content="text/html;  charset=gb2312">  
<title></title>  
</head>  
 
<body>  
<button  onClick="btnCount_Click()">計算相差天數</button>  
<script  language="JavaScript">  
 
   function  btnCount_Click(){  
       s1  =  "2002-1-10"  
       s2  =  "2002-10-1"  
       alert(DateDiff(s1,s2))  
   }  
 
   //計算天數差的函數,通用  
   function  DateDiff(sDate1,  sDate2){    //sDate1和sDate2是2002-12-18格式  
       var  aDate,  oDate1,  oDate2,  iDays  
       aDate  =  sDate1.split("-")  
       oDate1  =  new  Date(aDate[1]  +  '-'  +  aDate[2]  +  '-'  +  aDate[0])    //轉換為12-18-2002格式  
       aDate  =  sDate2.split("-")  
       oDate2  =  new  Date(aDate[1]  +  '-'  +  aDate[2]  +  '-'  +  aDate[0])  
       iDays  =  parseInt(Math.abs(oDate1  -  oDate2)  /  1000  /  60  /  60  /24)    //把相差的毫秒數轉換為天數  
       return  iDays  
}

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

在JavaScript中,計算當天日期后的幾天是什么日期。遠遠沒有在.Net中來的方便,一個函數就可以解決問題。就這個問題,把我困擾了一段時間,最終通過一個網友的介紹才把問題給解決掉。貼出來一起分享一下。

< script  language = " javascript "   type = " text/javascript " >   
var   startDate   =    new   Date  ();            var   intValue   =    0 ;  
var   endDate   =    null ;  
 
intValue  
=   startDate.getTime();            intValue   +=    100    *   ( 24    *    3600    *    1000 );  
endDate  
=    new   Date  (intValue);  
alert  (endDate.getFullYear()
+ " - " +  (endDate.getMonth() + 1 ) + " - " +  endDate.getDate());  
</ script >   


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

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM