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);
0

9 Answers 9

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

Reference to Date object

6
  • 2
    I had that suggestion, but the getTime function returns an undefined value. I don't think I quite understand the getTime(). Is that supposed to be a predefined function?
    – Lulu Ket
    Dec 3, 2008 at 20:22
  • 1
  • 3
    It seems like chrome and firefox supports date1 > date2, that is, without the getTime() part. Anyone know about the other browsers? Aug 2, 2011 at 14:52
  • @Linus I wouldn't trust the implementation to do it correctly. Better safe than sorry, aye? Nov 17, 2011 at 23:38
  • @JonathanDumaine Agreed, thought it looks much nicer :) Nov 19, 2011 at 17:16
15
new Date('1945/05/09').valueOf() < new Date('2011/05/09').valueOf()
3
  • working fine thanks Aug 9, 2016 at 8:29
  • @VladimirShmidt: It will not work in firefox.
    – Ajay Barot
    Dec 13, 2017 at 10:59
  • @AjayBarot have checked works good in lastest FireFox Jan 5, 2018 at 13:02
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.

10
  • 1
    what happens if the string cannot be parsed to a date?
    – Russ Cam
    Dec 3, 2008 at 19:57
  • 22
    This does not work with == (at least on firefox). Comparing two dates directly always returns false, you have to use getTime() as mentionned above. May 20, 2009 at 3: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 5, 2013 at 15:21
  • 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, 2015 at 22:44
  • 2
    ==, !=, ===, !=== do not work. Also, there is no !=== operator. Mar 24, 2015 at 10:34
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.

3

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

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

1
  • 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, 2021 at 4: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
}
1
  • 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 : developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…. 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, 2017 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 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. */

2
  • 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, 2011 at 15:25
  • This makes some large assumptions about date format and does not use international date standards.
    – Henry
    Feb 1, 2018 at 2:03
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;
}