js计算两个日期相差的天数

来源:互联网 发布:淘宝客鹊桥 编辑:程序博客网 时间:2024/04/28 21:23

<script type="text/javascript">
  function  btnCount_Click(){ 

     var cdate = new Date();
        var ddate = new Date(Date.parse('2014-08-23'));
  var year1=cdate.getFullYear();
  var Month1 = cdate.getMonth() + 1;
        var Day1 = cdate.getDate();
  var date1=year1+"-"+Month1+"-"+Day1;
  
     var year2=ddate.getFullYear();
  var Month2 = ddate.getMonth() + 1;
        var Day2 = ddate.getDate();
  var date2=year2+"-"+Month2+"-"+Day2;
  

  

       alert("相差"+DateDiff(date1,date2)+"天") 
   } 

   //计算天数差的函数,通用 
   function  DateDiff(sDate1,  sDate2){   
      //sDate1和sDate2是2006-12-18格式 
       var  aDate,  oDate1,  oDate2,  iDays 
       aDate  =  sDate1.split("-") 
       oDate1  =  new  Date(aDate[1]  +  '-'  +  aDate[2]  +  '-'  +  aDate[0])    //转换为12-18-2006格式 
       aDate  =  sDate2.split("-") 
       oDate2  =  new  Date(aDate[1]  +  '-'  +  aDate[2]  +  '-'  +  aDate[0]) 
       iDays  =  parseInt((oDate1  -  oDate2)  /  1000  /  60  /  60  /24)    //把相差的毫秒数转换为天数 
       return  iDays 
   }   

</script>

0 0