Cristy Cristy - 1 month ago 11
Javascript Question

Save and load date localstorage

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


I also tried
JSON.stringify
and
JSON.parse
trying to keep the date object intact, but that doesn't work either.

My guess is that I have to parse the date in the localStorage. If there is not a better method, how can I do that?

Answer

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.

Comments