SoFunction
Updated on 2025-03-01

JavaScript method to compare the number of days difference between two dates

This article describes the method of comparing the number of days between two dates. Share it for your reference. The details are as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http:///TR/html4/">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script language="JavaScript">
  function getDate(strDate){
    if(strDate==null||strDate===undefined) return null;
    var date = new Date();
    try{
      if(strDate == undefined){ 
        date= null;
      }else if(typeof strDate == 'string'){
        strDate = (/:/g,'-');
        strDate = (/ /g,'-');
        var dtArr = ("-");
        if(>=3&&<6){
          date=new Date(dtArr[0], dtArr[1], dtArr[2]);
        }else if(>8){
          date=new Date((dtArr[0],dtArr[1]-1,dtArr[2],dtArr[3]-8,dtArr[4],dtArr[5]));
        }
      }else{
        date = null;
      }
      return date;
    }catch(e){ 
      alert('Exception occurred in formatting date:' + ); 
    } 
  }
  function test(){
    var time1 = "2011-12-12";
    var time2 = "2011-12-10";
    var timeslong = getDate(time1).getTime()-getDate(time2).getTime();
    alert(timeslong/(1000*60*60*24))
  }
  test();
</script>
</head>
<body>
</body>
</html>

I hope this article will be helpful to everyone's JavaScript programming.