Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two dates in JavaScript

Tags:

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 start date. The date style, yyyy-mm-dd, needs to be kept in this format for other events prior to this. What is wrong with this code?

   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()
like image 660
Mick Avatar asked Nov 01 '09 17:11

Mick


1 Answers

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>
like image 91
Filipe Miguel Fonseca Avatar answered Oct 19 '22 23:10

Filipe Miguel Fonseca