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?
var date = window. localStorage. getItem("date"); date.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With