Save and load date localstorage
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.
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.