Two identical JavaScript dates aren't equal

前端 未结 3 514

When I create two identical JavaScript Date objects and then compare them, it appears that they are not equal. How to I test if two JavaScript dates have the sa

相关标签:
3条回答
  • 2020-12-03 10:42

    It appears this has been addressed already.

    To check whether dates are equal, they must be converted to their primitives:

    date1.getTime()=== date2.getTime()
    //true
    
    0 讨论(0)
  • 2020-12-03 10:46

    I compare many kinds of values in a for loop, so I wasn't able to evaluate them by substracting, instead I coverted values to string before comparing

    var a = [string1, date1, number1]
    var b = [string2, date2, number2]
    for (var i in a){
      if(a.toString() == b.toString()){
        // some code here
      }
    }
    
    0 讨论(0)
  • 2020-12-03 10:56

    First of all, you are making a sound mistake here of comparing the references. Have a look at this:

    var x = {a:1};
    var y = {a:1};
    
    // Looks like the same example huh!
    alert (x == y); // It says false
    

    Here, although the objects look identical but they hold diferent slots in memory. Reference store only the address of the object. Hence both references are different.

    So now, we have to compare the values since you know reference comparison won't work here. You can just do

    if (date1 - date2 == 0) {
        // Yep! Dates are equal
    } else {
       // Handle different dates
    }
    
    0 讨论(0)
提交回复
热议问题