js 日期相减

1.第一种

<html>
<body>
<head>
    <title>无标题页</title>
    <script type="text/javascript">

function DateDiff(sDate1,sDate2)
{
    var arrDate,objDate1,objDate2,intDays;
    arrDate=sDate1.split("-");
    objDate1=new Date(arrDate[1]+'-'+arrDate[2]+'-'+arrDate[0]);
    arrDate=sDate2.split("-");
    objDate2=new Date(arrDate[1] + '-'+arrDate[2]+'-'+arrDate[0]);
    intDays=parseInt(Math.abs(objDate1-objDate2)/1000/60/60/24);
    return intDays;
}
function check()
{

     var beginday = document.getElementById("Text1").value;
     var lastday = document.getElementById("Text4").value;
     var DayNum = DateDiff(beginday,lastday);
      alert(DayNum);     
     //就可以判断出相差的天数,然后你再判断时间,如果结束时间的小时数,小于开始时间的小时数,那么天数就减一天,开始小时数加24,不懂再问我
}

    </script>
</head>

<body>
    <form id="form1">

        
    开始日期:<input id="Text1" type="text" value="2010-7-12" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <input id="Text2" type="text" value="18" />时<input id="Text3" type="text"
        value="25" />分<br />
    <br />
    结束时间:<input id="Text4" type="text"  value="2010-7-30" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <input id="Text5" type="text" value="19" />时<input id="Text6" type="text"
        value="58" />分<br />
    <br />
    <input id="Button1" type="button" value="button" onclick="return check()" /></form>
</body>
</html>

2.第二种

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">    
  
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">    
<head>  
  <script type="text/javascript">  
    var getOffDays = function(startDate, endDate) {   
    var mmSec = (endDate.getTime() - startDate.getTime()); //得到时间戳相减 得到以毫秒为单位的差   
      return (mmSec / 3600000 / 24); //单位转换为天并返回   
    };   
    alert(getOffDays(new Date(2010,10,24), new Date(2010,12,3)));   
 
  </script>  
</head>  
<body>  
</body>  
</html> 

原文地址:https://www.cnblogs.com/dodui/p/1896700.html