SoFunction
Updated on 2025-04-10

Javascript sample code for judging the difference between two dates

For date difference, we need to convert the date difference such as 2015-08-30 into seconds, then use the second of two dates to subtract and then add it up to judge. If we judge that the dates are equal, it will be much simpler. There are examples at the end of the article.

Example 1, Date difference function

function better_time(strDateStart,strDateEnd){
  var strSeparator = "-"; //Date Separator  var strDateArrayStart;
  var strDateArrayEnd;
  var intDay;
  strDateArrayStart = (strSeparator);
  strDateArrayEnd = (strSeparator);
  var strDateS = new Date(strDateArrayStart[0] + "/" + strDateArrayStart[1] + "/" + strDateArrayStart[2]);
  var strDateE = new Date(strDateArrayEnd[0] + "/" + strDateArrayEnd[1] + "/" + strDateArrayEnd[2]);
  intDay = (strDateE-strDateS)/(1000*3600*24);
  return intDay;
 }

Example 2

function checkTime(){
   var dateInp=$("#dateInp").val();
   var day1=((/-/g, "/"));
   var nowDate = new Date();
   var dateStr = ()+"/"+(() + 1)+"/"+();        
   var day2=(dateStr);
   var apartTime=day1-day2;
   var apartDay=parseInt(apartTime / (1000 * 60 * 60 * 24));
   if(apartDay ==0){
     alert("Can't make an appointment on the same day");
     return false;
   }else if (apartDay < 1 || apartDay > 3){
     alert("Appointment date is out of range");
     return false;
   } 
 }

Determine that the date is equal

var date1 = new Date("2013-11-29");
 var date2 = new Date("2013-()11-29");
 (() == ()); //true

Be careful, don't write like this

var date1 = new Date("2013-11-29");
 var date2 = new Da()te("2013-11-29");
 (date1 == date2); //false

This is wrong, because after using new date, the date is the object, so the object cannot be compared like characters.