0

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
Justin
  • 26,443
  • 16
  • 111
  • 128

2 Answers2

4

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

Community
  • 1
  • 1
abc123
  • 17,855
  • 7
  • 52
  • 82
  • How can I compare them as dates instead of times then? Not possible? – Justin Jun 13 '15 at 04:29
  • @Justin you are comparing them as date objects with `ls_a === a` but since they aren't the same object this will return false. Comparing them as strings or numbers is the best solution in this scenario. – abc123 Jun 13 '15 at 05:00
1

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.

almightyGOSU
  • 3,731
  • 6
  • 31
  • 41