Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 902
XCS Avatar asked Sep 30 '12 12:09

XCS


People also ask

How do I get the localStorage date?

var date = window. localStorage. getItem("date"); date.

Does localStorage last forever?

localStorage is similar to sessionStorage , except that while localStorage data has no expiration time, sessionStorage data gets cleared when the page session ends — that is, when the page is closed.

Is it good to store data in localStorage?

No. localStorage is accessible by any webpage, and if you have the key, you can change whatever data you want. That being said, if you can devise a way to safely encrypt the keys, it doesn't matter how you transfer the data, if you can contain the data within a closure, then the data is (somewhat) safe.


2 Answers

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.

like image 114
techfoobar Avatar answered Oct 07 '22 20:10

techfoobar


To store a date in localStorage, simply do

localStorage['key'] = ''+myDate.getTime();

And to restore it :

var myDate = new Date(parseInt(localStorage['key'], 10));

(you might also want to test it's defined before)

It also works with duration (a date minus another one) : Simply use the value as long (millisecondes) and convert to and from a string.

Note that JSON doesn't include a standardized date format. Don't use JSON for dates.

like image 30
Denys Séguret Avatar answered Oct 07 '22 20:10

Denys Séguret