I have to save a date to localStorage and when the page is refreshed I want to calculate how much time has passed since then.
Now, here's the problem: localStorage saves the date as a string so after it is saved in localStorage trying to calculate the difference between those two dates returns NaN.
Try this in your javascript console:
var a = new Date();
var b = new Date();
console.log(b - a); //this works
localStorage.a = a;
localStorage.b = b;
console.log(localStorage.b - localStorage.a); //this doesn't work
JSON.stringify
JSON.parse
Demo: http://jsfiddle.net/AuhtS/
Code:
var a = new Date();
var b = new Date();
console.log(b - a); //this works
localStorage.a = a;
localStorage.b = b;
a = Date.parse(localStorage.a); // parse to date object
b = Date.parse(localStorage.b);
console.log(b - a); // now, this will work
Reason
Everything is stored as a string in localStorage
.
So when you do localStorage.b - localStorage.a
, what you're attempting is trying to subtract one string from another. Which is why it doesn't work.