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