views:

253

answers:

1

I must be missing something.

date1 = new Date(2010, 01, 10, 12, 10, 30, 000);
date2 = new Date(2010, 01, 10, 12, 10, 30, 000);

trace(date1 == date2); // returns false

However,

date1 = new Date(2010, 01, 10, 12, 10, 30, 000);
date2 = new Date(2010, 01, 10, 12, 10, 30, 000);

trace(date1.toString() == date2.toString()); // returns true

So... what's going on? Obviously the two date objects are somehow subtly different, and that difference somehow gets overlooked when they're parsed out as strings, but how are they different?

+1  A: 

When you compare two objects like this, what you are really comparing is their object identity, on a lower level, their positions in RAM. When you do new Date(), that creates a new object, so the two objects will not match, even though the values stored therein do.

Comparing strings however is a special case where the strings are compared character-by-character rather than comparing their positions in memory.

A common way to compare dates is using their time property, which is a Number representing the Date object as UNIX time, i.e. seconds since the start of the UNIX epoch at 1970-01-01 00:00:00.

trace(date1.time == date2.time); // traces "true"

Cheers

richardolsson
crazy - I guess I thought that kind of comparison only took place if you use the '===' operator - that '==' compares values, '===' compares the actual unique variables themselves. But not so much, huh? Good to know, thanks!
matt lohkamp
The `==` and `===` operators are identical (apart from strings, I think, and even then they can be interned). The flash runtime has no support for overriding equality so `==` is always a reference comparision.
Richard Szalay