Skip to content Skip to sidebar Skip to footer

Compare Two Dates In Javascript

I am trying to compare two dates. I have this code which I thought would work a treat, but it didn't. For now I just want to alert with an error if the end date is less than the st

Solution 1:

Try using DateJS, an open-source JavaScript Date Library that can handle pretty much everything! The following example is working:

<scripttype="text/javascript"src="date.js"></script><script>

    startdate = "2009-11-01";
    enddate  = "2009-11-04"; 

    var d1 = Date.parse(startdate);
    var d2 = Date.parse(enddate) ;

    if (d1 < d2) {
        alert ("Error!");
    }

</script>

Solution 2:

Someone finally uses ISO 8601 standard dates but then ...

You are using a nice international standard that JavaScript arguably should understand. But it doesn't.

The problem is that your dates are in ISO 8601 standard format which the built-in Date.parse() can't read.

JavaScript implements the older IETF dates from RFC 822/1123. One solution is to tweak them into the RFC-style, which you can see in RFC1123, and which look like dd month yyyy.

There is coding floating about that can scan the ISO format comprehensively, and now that you know to google for "iso standard date" you can get it. Over here I found this:

Date.prototype.setISO8601 = function (string) {
    var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
        "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
        "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
    var d = string.match(newRegExp(regexp));

    var offset = 0;
    var date = newDate(d[1], 0, 1);

    if (d[3]) { date.setMonth(d[3] - 1); }
    if (d[5]) { date.setDate(d[5]); }
    if (d[7]) { date.setHours(d[7]); }
    if (d[8]) { date.setMinutes(d[8]); }
    if (d[10]) { date.setSeconds(d[10]); }
    if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
    if (d[14]) {
        offset = (Number(d[16]) * 60) + Number(d[17]);
        offset *= ((d[15] == '-') ? 1 : -1);
    }

    offset -= date.getTimezoneOffset();
    time = (Number(date) + (offset * 60 * 1000));
    this.setTime(Number(time));
}

js> t = newDate()
SunNov01200909:48:41GMT-0800 (PST)
js> t.setISO8601("2009-11-01")
js> t

SatOct31200917:00:00GMT-0700 (PDT)

The 11-01 is reinterpreted in my timezone, as long as all your dates get the same conversion then they should compare reasonably, otherwise you can add TZ info to your string or to the Date object.

Solution 3:

The Date constructor cannot parse that format, and since you cannot change it, you should parse it manually, and pass the year, month and date parts to it, for example:

functioncompareDates(startDate, endDate) {

  // parse a date in yyyy-mm-dd formatfunctionparseDate(input) {
    var parts = input.match(/(\d+)/g);
    returnnewDate(parts[0], parts[1]-1, parts[2]); // months are 0-based
  }

  if (parseDate(endDate) < parseDate(startDate)) {
    alert ("Error !");
  }
}

Usage:

var startDate = "2009-11-01",
    endDate = "2009-11-04";
compareDates(startDate, endDate);    

Solution 4:

var myDate=newDate();
myDate.setFullYear(2010,0,14);
var today = newDate();

if (myDate>today)
{
    alert("Today is before 14th January 2010");
}
else
{
    alert("Today is after 14th January 2010");
}

source: http://www.w3schools.com/jS/js_obj_date.asp

Solution 5:

If you only need to know if one date comes before the other, you could just use the Date object's getTime() method to compare their respective numbers of milliseconds since midnight Jan 1, 1970:

if( d2.getTime() < d1.getTime() )
{
    alert("eeeek!");
}

--- Don't get mixed up and try to use getMilliseconds(), though :)

w3schools documentation on getTime()

Post a Comment for "Compare Two Dates In Javascript"