Jos*_*han 5 javascript jquery html5 date local-storage
我将日期存储到本地存储,如下所示.
JS:
var currentTime = new Date(); //get the current time.
//Clock in the time.
localStorage.time = currentTime;
Run Code Online (Sandbox Code Playgroud)
当我尝试稍后使用时检索它...
var timeObj = new Date(localStorage.time);
var checkInDayOfMonth = timeObj.getUTCDate(); //returns 1-31
Run Code Online (Sandbox Code Playgroud)
timeObj将没有正确的日期时间,而是显示当前时间,好像它忽略了我发送的时间参数.
我正在使用getUTCDate来获取当月的这一天.如果今天的价值与存储的价值不同,我知道这是新的一天.
打开Google Chrome Inspector会以以下格式显示以localStorage存储的日期:
Wed Dec 11 2013 22:17:45 GMT-0800 (PST)
Run Code Online (Sandbox Code Playgroud)
这不是日期构造函数的可接受格式吗?
如何正确存储和检索localStorage中的日期?
Zla*_*tko 13
您可以将其作为unix时间戳返回.确保将数字传递给Date构造函数.
首先,保存.添加+到new,使其成为时间戳.
localStorage.setItem('time', +new Date);
Run Code Online (Sandbox Code Playgroud)
然后后来检索它,但将数字传递给Date构造函数:
new Date(parseInt(localStorage.getItem('time')));
Run Code Online (Sandbox Code Playgroud)