且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

保存并加载日期localstorage

更新时间:2023-02-02 19:34:57

演示: 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.