tags:

views:

152

answers:

4

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 an error if the enddate is less than the start date . The date style yyyy-mm-dd needs to be kept in this format for other events prior to this. can anyone give me a clue ? thanks

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

   var d1 = new Date(startdate)
   var d2 = new Date(enddate) 

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


   document.cookie='st =' + startdate // set sytem cookie 
   document.cookie='en =' + enddate
   window.location = self.location.href
   window.opener.location.reload()
   close()
+2  A: 

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:

function compareDates(startDate, endDate) {

  // parse a date in yyyy-mm-dd format
  function parseDate(input) {
    var parts = input.match(/(\d+)/g);
    return new Date(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);
CMS
+1 for a start to finish solution, but I'm not really thrilled about the function declaration within a function. (To be honest I'm not even really thrilled about function declarations anywhere in Javascript.)
eyelidlessness
@eyelidlessness: JavaScript has function-scope only, it has no block-scope as other languages, declaring the function within a function, makes `parseDate` local, and keeps clean the global namespace. Of course if you intend to use `parseDate` on other functions, you will have to put it somewhere else. :-)
CMS
+2  A: 
var myDate=new Date();
myDate.setFullYear(2010,0,14);
var today = new Date();

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%5Fobj%5Fdate.asp

Chris Ballance
+2  A: 

Someone finally uses ISO standard dates but then ...

You are using a nice international standard that JS 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 RFC822/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(new RegExp(regexp));

    var offset = 0;
    var date = new Date(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 = new Date()
Sun Nov 01 2009 09:48:41 GMT-0800 (PST)
js> t.setISO8601("2009-11-01")
js> t

Sat Oct 31 2009 17:00:00 GMT-0700 (PDT)

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

DigitalRoss
+1  A: 

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

<script type="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>
Miguel Fonseca