Forum Moderators: open

Message Too Old, No Replies

why no Date() match?

         

Wayder

12:50 pm on Mar 2, 2012 (gmt 0)

10+ Year Member Top Contributors Of The Month



1. var val = "2012-2-8,2012-2-10,2012-2-9"; // take string
2. val = val.split(','); // change to array
3. for (var i = 0; i < val.length ; i++ ){
4. var dateChange = val[i].split('-');
5. val[i] = new Date(dateChange[0],dateChange[1]-1,dateChange[2]); // make date from string
6. }
7. val.sort(date_sort_asc); // sort in date order (external function)
8. var valLength = val.length;
9. var tomorrow = new Date("2012","0","10");
10. for (var i = 0; i < valLength ; i++ ){
11. if(val[i] == tomorrow){ // why no match?
12. alert("Dates ==");
13. }else if(val[i] > tomorrow){ // works fine
14. alert("Dates >");
15. }else if(val[i] < tomorrow){ // works fine
16. alert("Dates <");
17. }else{
18. alert("Arrrrrgggggg !");
19. }
20. tomorrow = new Date(val[i].getFullYear(),val[i].getMonth(),val[i].getDate()+1);
21. }


Can anyone explain to me why the dates don't match on line 10 please. As far as I can see, they are the same.

Thanks

Ray...

Fotiman

3:19 pm on Mar 2, 2012 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You're comparing 2 Date objects, as opposed to comparing the value of those objects. You have 2 different objects that both may contain the same value, but the objects themselves are not the same object.

To compare the value of Date objects, do the comparison on the result of getTime():

if(val[i].getTime() == tomorrow.getTime())

Wayder

4:38 pm on Mar 2, 2012 (gmt 0)

10+ Year Member Top Contributors Of The Month



Thank you.

Time to read a little I think.