保存并加载日期localstorage [英] Save and load date localstorage
问题描述
我必须将日期保存到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.
现在,问题出在这里: localStorage将日期保存为字符串,因此在localStorage中保存之后,尝试计算这两个日期之间的差异返回NaN。
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.
在javascript控制台中尝试:
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
我也试过 JSON.stringify
和 JSON.parse
试图保持日期对象不变,但这也不起作用。
I also tried JSON.stringify
and JSON.parse
trying to keep the date object intact, but that doesn't work either.
我的猜测是我必须在localStorage中解析日期。如果没有更好的方法,我该怎么做?
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?
推荐答案
演示: http://jsfiddle.net/AuhtS/
代码:
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
原因
所有内容都存储为 localStorage
中的字符串。
Everything is stored as a string in localStorage
.
因此,当您执行 localStorage.b - localStorage.a
时,您尝试的是尝试从另一个字符串中减去一个字符串。这就是为什么它不起作用。
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.
这篇关于保存并加载日期localstorage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!