Here I thought comparing two dates via <=> would invoke the toString method of the date object and end up comparing the strings returned.
Nope, compares them via valueOf, which for Date is the same as getTime.
It sure would be nice if I knew what part of say, Firefox or Chrome source code I should look at to find out.
No need to sort through source code, the specification (ecma-international .org / publications / standards / Ecma-262.htm) is clear, you just have to cross-reference sections. Start with 11.8.5 ("The Abstract Relational Comparison Algorithm") that tells us the values will be compared using the [[ToPrimitive]] operation with the "hint" Number. Head over to section 9.1 ("ToPrimitive") and it tells us that for Objects, [[ToPrimitive]] just passes through to [[DefaultValue]], passing on the hint. Head over to 8.12.8 ("DefaultValue (hint)") and it tells us if the hint is Number and the object has a valueOf, it'll use valueOf. So check out Date's valueOf (18.104.22.168 ) and it says it returns "this time value" which is the spec's way of saying the number of milliseconds since The Epoch (read the introduction to the Date object [15.9.1, 22.214.171.124] to verify that). Conveniently, the very next section (126.96.36.199) is getTime, which says the same thing.
(Those section numbers are from the new 5th edition spec, but the ECMA were very smart and avoided changing section numbers where they could. In the 3rd edition spec, the only different one is that "[[DefaultValue]] (hint)" is 188.8.131.52 instead of 8.12.8.)
It's also trivial to prove this experimentally:
var d1, d2;
d1 = new Date(2010, 10, 1);
d2 = new Date(2009, 10, 3);
write("d1: " + d1);
// Writes "Mon Nov 01 2010 00:00:00 GMT+0000 (GMT Standard Time)"
write("d2: " + d2);
// Writes "Tue Nov 03 2009 00:00:00 GMT+0000 (GMT Standard Time)"
write(d1 > d2);
// writes "true", d1 is in 2010, d2 is in 2009
write(d1.toString() > d2.toString());
// writes "false", d1's string starts with an "M", d2's with a "T"; "M" < "T"
As you can see, it's not using toString when relationally comparing Date instances.
(In the above,
write is whatever output mechanism you want to use; it should be sure to treat what it gets as a String, or it may output -1 instead of true and 0 instead of false -- comes to the same thing, but it's less clear.)