How do I do a Date comparison in Javascript? [duplicate]
Asked Answered
S

9

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);
Superabundant answered 3/12, 2008 at 19:43 Comment(0)
V
235
if (date1.getTime() > date2.getTime()) {
    alert("The first date is after the second date!");
}

Reference to Date object

Vitrescent answered 3/12, 2008 at 19:49 Comment(6)
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?Superabundant
hope this helps comptechdoc.org/independent/web/cgi/javamanual/javadate.htmlProbst
It seems like chrome and firefox supports date1 > date2, that is, without the getTime() part. Anyone know about the other browsers?Dillie
@Linus I wouldn't trust the implementation to do it correctly. Better safe than sorry, aye?Versatile
@JonathanDumaine Agreed, thought it looks much nicer :)Dillie
valuleOf is more reliableScrivener
J
15
new Date('1945/05/09').valueOf() < new Date('2011/05/09').valueOf()
Jahvist answered 27/5, 2011 at 7:6 Comment(3)
working fine thanksSagacity
@VladimirShmidt: It will not work in firefox.Musicianship
@AjayBarot have checked works good in lastest FireFoxJahvist
E
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.

Euripus answered 3/12, 2008 at 19:50 Comment(10)
what happens if the string cannot be parsed to a date?Twannatwattle
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".Euripus
This does not work with == (at least on firefox). Comparing two dates directly always returns false, you have to use getTime() as mentionned above.Chainplate
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()); trueLassiter
'===' compares object references and won't work.Banka
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.Prisage
==, !=, ===, !=== do not work. Also, there is no !=== operator.Aeroembolism
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.Primrose
@Primrose actually >, <, <=, and >= do work for comparing dates.Saavedra
@Prisage That is because new Date("13/1/2015") returns Invalid Date -_-Endolymph
H
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.

Hypotaxis answered 3/12, 2008 at 19:49 Comment(0)
B
3

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

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

Bolivia answered 5/12, 2008 at 3:37 Comment(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.Detrimental
K
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
}
Kelila answered 19/12, 2011 at 22:16 Comment(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.Including
R
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;
}  
Reiko answered 27/5, 2010 at 12:37 Comment(0)
E
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. */

Epaminondas answered 25/8, 2011 at 7:30 Comment(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.Caesarism
This makes some large assumptions about date format and does not use international date standards.Pavla
M
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"; 
                  }
                 }
                }
Multiplicand answered 4/6, 2012 at 9:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.