2

Why doesn't this work right?

function test() { 
    var start = new Date(2012, 3, 31, 19, 0, 0); // 3/31/2012 7:00 PM
    var end = new Date(2012, 4, 1, 1, 0, 0);     // 4/01/2012 1:00 AM

    if (end < start)
        console.log("oops!");
    else
        console.log("works!");
}

Output:

oops!

peter
  • 6,067
  • 2
  • 33
  • 44
  • 1
    possible duplicate of [JavaScript Date Object Comparison](http://stackoverflow.com/questions/7606798/javascript-date-object-comparison) – Pekka Mar 23 '12 at 17:11
  • 2
    Why is this a bug? Your start is actually after your end given the dates you've created. 3 is April, which only has 30 days, but you've set the date to 31, which makes it May. Months use a 0 index. – kinakuta Mar 23 '12 at 17:12
  • 1
    @AdrianIftode - No, 3 is for April - Months are 0-based. – Jakub Konecki Mar 23 '12 at 17:25

3 Answers3

9

Months are 0-based in js

var start = new Date(2012, 2, 31, 19, 0, 0); // 3/31/2012 7:00 PM
var end = new Date(2012, 3, 1, 1, 0, 0);     // 4/01/2012 1:00 AM

In your case both start and end are 1 May 2012. Just output the values and you'll see.

Jakub Konecki
  • 45,581
  • 7
  • 87
  • 126
3

Your dates actually resolve to

Tue May 01 2012 19:00:00 GMT-0700 (PDT)
Tue May 01 2012 01:00:00 GMT-0700 (PDT)

From DateMDN:

month
Integer value representing the month, beginning with 0 for January to 11 for December.

calebds
  • 25,670
  • 9
  • 46
  • 74
0

I assume you want to see which date comes before the other, right?

When you compare the two you aren't comparing the actual dates you're comparing objects. Try if(end.valueOf() < start.valueOf()) { //do stuff }

hradac
  • 2,431
  • 1
  • 19
  • 21