Home > Web Front-end > JS Tutorial > body text

JavaScript sample code to determine the difference between two dates_time and date

WBOY
Release: 2016-05-16 15:40:55
Original
1192 people have browsed it

We need to convert the date difference such as 2015-08-30 into seconds like in PHP, then use the seconds of the two dates to subtract and then add them together to judge. If the dates are equal, it is simple. There are more examples at the end of the article.

Example 1, date difference function

function better_time(strDateStart,strDateEnd){
  var strSeparator = "-"; //日期分隔符
  var strDateArrayStart;
  var strDateArrayEnd;
  var intDay;
  strDateArrayStart = strDateStart.split(strSeparator);
  strDateArrayEnd = strDateEnd.split(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;
 }
Copy after login

Example 2

function checkTime(){
   var dateInp=$("#dateInp").val();
   var day1=Date.parse(dateInp.replace(/-/g, "/"));
   var nowDate = new Date();
   var dateStr = nowDate.getFullYear()+"/"+(nowDate.getMonth() + 1)+"/"+nowDate.getDate();        
   var day2=Date.parse(dateStr);
   var apartTime=day1-day2;
   var apartDay=parseInt(apartTime / (1000 * 60 * 60 * 24));
   if(apartDay ==0){
     alert("不能预约当天");
     return false;
   }else if (apartDay < 1 || apartDay > 3){
     alert("预约日期超出范围");
     return false;
   } 
 }
Copy after login

Judge that the dates are equal

var date1 = new Date("2013-11-29");
 var date2 = new Date("2013-(www.jb51.net)11-29");
 console.log(date1.getTime() == date2.getTime()); //true
Copy after login

Attention, please don’t write like this

var date1 = new Date("2013-11-29");
 var date2 = new Da(www.jb51.net)te("2013-11-29");
 console.log(date1 == date2); //false
Copy after login

This is wrong, because after using new date, the date becomes an object, and the objects cannot be compared like characters.

Related labels:
js
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template