Testing date equality in JS

the BlogFather (Dave Winer) posts an observation about Testing date equality in JS  to the effect that it doesn’t work as expected.. (silly me, I have comments)

ie that :

var d1 = new Date ("March 12, 1994");
var d2 = new Date ("March 12, 1994");
alert (d1 == d2); // false

So, a couple of things :

  • == tests object equivalence,
  • === tests value equivalence
  • so d1 is a different object from d2
  • generally you want to do === not == (even for js primitives)
for any object, you want to think about how .toString or .valueFor evaluates. for a date object :
  • d1.getTime() == d2.getTime()
  • d1.valueOf() == d2.valueOf()
  • +d1 == +d2 (I think the + operator is doing a casting?)
  • Number(d1) == Number(d2) using the Number object to return the value
all work (for === as well, which would be my default choice for testing equivalence.)

see also JavaScript “loose” comparison step by step

Leave a Reply