Home >Web Front-end >JS Tutorial >JavaScript sample code to determine the difference between two dates_time and date
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; }
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; } }
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
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
This is wrong, because after using new date, the date becomes an object, and the objects cannot be compared like characters.