2
votes

I need to compare dates in javascript. After attempt many ways... I choose:

    var endDate = new Date(secondDate.getYear(), secondDate.getMonth(), secondDate.getDate(), 0, 0, 0,0);

    var startDate = new Date(firstDate.getYear(), firstDate.getMonth(), firstDate.getDate(), 0, 0, 0, 0);

    if (endDate.getTime() >= startDate.getTime()) {
        isValid = true;
    }
    else {
        isValid = false;
    }

In my situation:

---startDate = Tue Apr 01 1997 00:00:00 GMT+0200 (Jerusalem Standard Time) (i.e, 01/04/1997)

---endDate = Thu Jul 26 114 00:00:00 GMT+0200 (Jerusalem Standard Time) (i.e, 26/07/2014)

You see? startDate is small then endDate, right?

But:

---endDate.getTime() returns: -58551904800000

---startTime.getTime() returns: 859845600000

so, endDate.getTime() >= startDate.getTime() returns false...

In other situation, it works well:

---startDate: Sat Jul 21 114 00:00:00 GMT+0200 (Jerusalem Standard Time) (i.e, 21/07/2014)

---endDate: Sat Jul 28 114 00:00:00 GMT+0200 (Jerusalem Standard Time) (i.e, 28/07/2014)

---startDate.getTime() returns -58552336800000

---endDate.getTime() returns -58551732000000

so, endDate.getTime() >= startDate.getTime() returns true...

It seems like that javascript functions have another behavior for dates after year 2000.

What should I do? which code will be match to all of the optional situations?

Thanks.

3

3 Answers

0
votes

Yeah like ghusse said, there is a problem with your end time if you fixed it so it was 2014 you would get a result such as 1406329200000 instead of -58551904800000

0
votes

I found a solution, after I read Josh and ghusse answers and advice:

Use getFullYear(), instead getYear(), and all will work O.K.

0
votes

Apparently, you have a problem with your end dates :

Thu Jul 26 114 00:00:00 GMT+0200

Does not mean 21/07/2014 but 21/07/114

According to the doc, here are 2 correct ways of creating your date:

var endDate = new Date(21, 6, 2014);

// Or a string corresponding to a version of ISO8601
var endDate = new Date('2014-07-21T00:00:00z+3');