118

I would like to compare two dates in javascript. I have been doing some research, but all I can find is how to return the current date. I want to compare 2 separate dates, not related to today. How do I do that.

var startDate = Date(document.form1.Textbox2);
Samuel Liew
  • 76,741
  • 107
  • 159
  • 260

9 Answers9

234
if (date1.getTime() > date2.getTime()) {
    alert("The first date is after the second date!");
}

Reference to Date object

matt b
  • 138,234
  • 66
  • 282
  • 345
15
new Date('1945/05/09').valueOf() < new Date('2011/05/09').valueOf()
Vladimir Shmidt
  • 2,651
  • 1
  • 19
  • 21
10

JavaScript's dates can be compared using the same comparison operators the rest of the data types use: >, <, <=, >=, ==, !=, ===, !==.

If you have two dates A and B, then A < B if A is further back into the past than B.

But it sounds like what you're having trouble with is turning a string into a date. You do that by simply passing the string as an argument for a new Date:

var someDate = new Date("12/03/2008");

or, if the string you want is the value of a form field, as it seems it might be:

var someDate = new Date(document.form1.Textbox2.value);

Should that string not be something that JavaScript recognizes as a date, you will still get a Date object, but it will be "invalid". Any comparison with another date will return false. When converted to a string it will become "Invalid Date". Its getTime() function will return NaN, and calling isNaN() on the date itself will return true; that's the easy way to check if a string is a valid date.

user247702
  • 23,641
  • 15
  • 110
  • 157
Will Wagner
  • 4,128
  • 3
  • 22
  • 14
  • 1
    what happens if the string cannot be parsed to a date? – Russ Cam Dec 03 '08 at 19:57
  • Then you still get a Date object, but it's invalid. Any comparison with another date will return false. Its getTime() function will return NaN, and calling isNaN() on the date itself will return true. When converted to a string it will become "Invalid Date". – Will Wagner Dec 04 '08 at 13:09
  • 21
    This does not work with == (at least on firefox). Comparing two dates directly always returns false, you have to use getTime() as mentionned above. – Luper Rouch May 20 '09 at 03:36
  • 2
    In Visual Studio 2010 javascript debugger: `?(new Date('1995-02-04T24:00') == new Date('1995-02-05T00:00')); false` but `?(new Date('1995-02-04T24:00').getTime() == new Date('1995-02-05T00:00').getTime()); true` – Tim Feb 05 '13 at 15:21
  • '===' compares object references and won't work. – Torleif Dec 05 '14 at 09:48
  • 6
    new Date("12/1/2015") !== new Date("12/1/2015"), so saying you compare javascript dates like 'the rest of the data types' is at best misleading. Downvoted. – Isak Feb 11 '15 at 22:44
  • 2
    ==, !=, ===, !=== do not work. Also, there is no !=== operator. – Evgeni Nabokov Mar 24 '15 at 10:34
  • 1
    none of these operators should work. Since date is a complex type, `==` compares the value, in this case the instance reference of the date created. `===` compares type as well as reference. – eggmatters Aug 07 '15 at 16:55
  • @eggmatters actually `>`, `<`, `<=`, and `>=` do work for comparing dates. – Andy Nov 26 '16 at 16:19
  • @Isak That is because new Date("13/1/2015") returns Invalid Date -_- – Marcos Pereira May 12 '18 at 14:17
4

You can use the getTime() method on a Date object to get the timestamp (in milliseconds) relative to January 1, 1970. If you convert your two dates into integer timestamps, you can then compare the difference by subtracting them. The result will be in milliseconds so you just divide by 1000 for seconds, then 60 for minutes, etc.

Marc Novakowski
  • 44,628
  • 11
  • 58
  • 63
3

I would rather use the Date valueOf method instead of === or !==

Seems like === is comparing internal Object's references and nothing concerning date.

  • I like this method as it correctly interprets the datetime into milliseconds since 1 January 1970 00:00:00 UTC, and therefore doing something like myDate.valueOf() == anotherDate.valueOf() can exactly match to the millisecond. – Gwasshoppa Sep 29 '21 at 04:45
1
function fn_DateCompare(DateA, DateB) {     // this function is good for dates > 01/01/1970

    var a = new Date(DateA);
    var b = new Date(DateB);

    var msDateA = Date.UTC(a.getFullYear(), a.getMonth()+1, a.getDate());
    var msDateB = Date.UTC(b.getFullYear(), b.getMonth()+1, b.getDate());

    if (parseFloat(msDateA) < parseFloat(msDateB))
      return -1;  // lt
    else if (parseFloat(msDateA) == parseFloat(msDateB))
      return 0;  // eq
    else if (parseFloat(msDateA) > parseFloat(msDateB))
      return 1;  // gt
    else
      return null;  // error
}
DaveShaw
  • 52,123
  • 16
  • 112
  • 141
  • 1
    Adding one to `a/b.getMonth()` causes January which is `0` to become `1`, which translates as February to the Date.UTC method. See the mdn article : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC. The section on acceptable values for the `month` parameter. Try to compare, for example, the dates '2/1/2017' and '1/31/2017' using your function. – papiro Jan 26 '17 at 19:49
0
    function validateform()
    {
     if (trimAll(document.getElementById("<%=txtFromDate.ClientID %>").value) != "") {
   if (!isDate(trimAll(document.getElementById("<%=txtFromDate.ClientID %>").value)))
         msg = msg + "<li>Please enter valid From Date in mm/dd/yyyy format\n";
   else {
       var toDate = new Date();
       var txtdate = document.getElementById("<%=txtFromDate.ClientID %>").value;
       var d1 = new Date(txtdate)
   if (Date.parse(txtdate) > Date.parse(toDate)) {                   
         msg = msg + "<li>From date must be less than or equal to today's date\n";
   }
  }
}

     if (trimAll(document.getElementById("<%=txtToDate.ClientID %>").value) != "") {
            if (!isDate(trimAll(document.getElementById("<%=txtToDate.ClientID %>").value)))
                msg = msg + "<li>Please enter valid To Date in mm/dd/yyyy format\n";
            else {
                var toDate = new Date();
                var txtdate = document.getElementById("<%=txtToDate.ClientID %>").value;
                var d1 = new Date(txtdate)

                if (Date.parse(txtdate) > Date.parse(toDate)) {
                    msg = msg + "<li>To date must be less than or equal to today's date\n"; 
                  }
                 }
                }
0

You could try adding the following script code to implement this:

if(CompareDates(smallDate,largeDate,'-') == 0) {
    alert('Selected date must be current date or previous date!');
return false;
}

function CompareDates(smallDate,largeDate,separator) {
    var smallDateArr = Array();
    var largeDateArr = Array(); 
    smallDateArr = smallDate.split(separator);
    largeDateArr = largeDate.split(separator);  
    var smallDt = smallDateArr[0];
    var smallMt = smallDateArr[1];
    var smallYr = smallDateArr[2];  
    var largeDt = largeDateArr[0];
    var largeMt = largeDateArr[1];
    var largeYr = largeDateArr[2];

    if(smallYr>largeYr) 
        return 0;
else if(smallYr<=largeYr && smallMt>largeMt)
    return 0;
else if(smallYr<=largeYr && smallMt==largeMt && smallDt>largeDt)
    return 0;
else 
    return 1;
}  
thejartender
  • 9,339
  • 6
  • 34
  • 51
0

You can try this code for checking which date value is the highest from two dates with a format MM/DD/YYYY:

function d_check() {
    var dl_sdt=document.getElementIdBy("date_input_Id1").value; //date one
    var dl_endt=document.getElementIdBy("date_input_Id2").value; //date two

    if((dl_sdt.substr(6,4)) > (dl_endt.substr(6,4))) {
        alert("first date is greater");
        return false;
    }

    else if((((dl_sdt.substr(0,2)) > (dl_endt.
        substr(0,2)))&&(frdt(dl_sdt.substr(3,2)) > (dl_endt.substr(3,2))))||
        (((dl_sdt.substr(0,2)) > (dl_endt.substr(0,2)))&&
        ((dl_sdt.substr(3,2)) < (dl_endt.substr(3,2))))||
        (((dl_sdt.substr(0,2)) == (dl_endt.substr(0,2)))&&((dl_sdt.substr(3,2)) > 
        (dl_endt.substr(3,2))))) {
            alert("first date is greater");
        return false;
    }

    alert("second date is digher");
    return true;
}

/*for checking this....create a form and give id's to two date inputs.The date format should be mm/dd/yyyy or mm-dd-yyyy or mm:dd:yyyy or mm.dd.yyyy like this. */

thejartender
  • 9,339
  • 6
  • 34
  • 51
  • Very good function, except for one little thing. An assumption is made that the user input will always follow a given date pattern (the use of sub-strings). I think I might use this, though with some input validation, thank you. – Kingsolmn Nov 18 '11 at 15:25
  • This makes some large assumptions about date format and does not use international date standards. – Henry Feb 01 '18 at 02:03