JavaScript Date mismatch after being stored as string

167 views Asked by At

I cannot figure out why ls_a === a is returning false in the code below. It seems like when I convert to a date to string and back to date, something is being lost, but what??

JSFiddle: http://jsfiddle.net/s6accbax/

var a = new Date();
localStorage.a = a.getTime();
ls_a = new Date(parseInt(localStorage.a));

console.log(a);    // Fri Jun 12 2015 22:12:34 GMT-0600 (MDT)
console.log(ls_a); // Fri Jun 12 2015 22:12:34 GMT-0600 (MDT)
console.log(ls_a === a); // returns false!?!?!
console.log(ls_a.getTime() === a.getTime()); // returns true as expected
2

There are 2 answers

2
abc123 On BEST ANSWER

Duplicate of: JavaScript Date Object Comparison

This is because ls_a is a different object than a when you call .getTime() you are getting a string which isn't compared as an object

1
almightyGOSU On

There is no type conversion when you use ===, and therefore, ls_a is not equivalent to a.

The strict equality operator === only considers values equal that have the same type.