Comparing equalities between date and number does not work

According to the ECMA script standard, the following code should return true, but it is not:

d = new Date() ; d.setTime(1436497200000) ; alert( d == 1436497200000 ) ; 

Section 11.9.3 says:

  1. If Type (x) is either String or Number and Type (y) is Object, return the result of the comparison x == ToPrimitive (y).

Then, in section 8.12.8 , ToPrimitive readjusts the result of the valueOf method. This means that the last line in my example above should be equivalent:

 alert( d.valueOf() == 1436497200000 ); 

Which really returns true .

Why does the first case not return true ?

+8
javascript comparison date-comparison
source share
2 answers

If you look at the spec in section 8.12.8 , you will find this text at the end of the section:

When the [[DefaultValue]] O internal method is called without a hint, it behaves as if the hint was Number , if O not a Date object, see 15.9.6), in which case it behaves as if a hint was String .

(Emphasis mine)

Now in step 8/9 of the Abstract Equality Comparison Algorithm [ 11.9.3 ], ToPrimitive(x) and ToPrimitive(y) are called without the hint parameter.

The absence of this hint parameter along with the text above means that the ToPrimitive method returns the value toString() for date objects.

As you probably know, (new Date()).toString() returns a string representation of the date in American English [ source ] :
"Wed Jul 01 2015 22:08:41 GMT+0200 (W. Europe Daylight Time)"

That a line like this is not equal to 1436497200000 should not come as a big surprise .; -)

+5
source share

ToPrimitive (A) tries to convert its object argument to a primitive value, trying to call different sequences of A.toString and A.valueOf methods on A.

So, if the call toString() succeeds, it will not call valueOf() .

0
source share

All Articles