Save and load localstorage date

I need to save the date in localStorage, and when the page refreshes, 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 saving it to localStorage trying to calculate the difference between the 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.

I assume that I need to parse the date in localStorage. If there is no better method, how can I do this?

+13
source share
6 answers

Demo: http://jsfiddle.net/AuhtS/

The 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 

Cause

Everything is stored as a string in localStorage .

So, when you do localStorage.b - localStorage.a , what you are trying is trying to subtract one line from another. That is why it does not work.

+40
source

To save the date in localStorage just do

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

And restore it:

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

(you can also check it earlier)

It also works with a duration (minute minus another): just use a value (milliseconds) long and convert to and from a string.

Please note that JSON does not include a standardized date format. Do not use JSON for dates.

+8
source

http://rhaboo.org is a layer of sugar on top of localStorage that (among many other things) fixes such things. You just write:

 var store = Rhaboo.persistent("My Store Name"); console.log ( "Your last visit was " + store.datestamp || "never."); store.write('datestamp', new Date()); 

By the way, I wrote rhaboo.

+2
source

I would use this:

 var d1 = new Date(); localStorage.setItem("key", d1.getTime()); var d2 = new Date(parseInt(localStorage.getItem[key])); 

all that is missing is a proper zero check.

+1
source

You can just go:

 var date1 = <date1> var date2 = <date2> localStorage.setItem('date1', date1.toString()) localStorage.setItem('date2', date2.toString()) var date1 = new Date(localStorage.getItem('date1')) var date2 = new Date(localStorage.getItem('date2')) var diff = date1 - date2 
0
source

In my case, this is needed in the Date type. So here it is:

 var a = new Date(); localStorage.a = a; var c = new Date(localStorage.a); 
0
source

All Articles