Javascript sample code for judging the difference between two dates

Source: Internet
Author: User

Javascript sample code for judging the difference between two dates

We need to convert the date difference to seconds like in php, such as, and then subtract the seconds of the two dates and then add a judgment, if the judgment date is equal, it is much simpler. Examples are provided at the end of this article.

Example 1: Date difference function

Function better_time (strDateStart, strDateEnd) {var strSeparator = "-"; // Date delimiter 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 dateindium = $ ("# dateindium "). val (); var day1 = Date. parse (dateindium. 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 ("the current day cannot be booked"); return false;} else if (apartDay <1 | apartDay> 3) {alert ("the reservation date is out of the range "); return false ;}}

Equal date

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

Note: Do not write it 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 the date after new date is the object, so the object cannot be compared as the character.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.