存储日期并从本地存储中检索
我将日期存储到本地存储,如下所示。
JS:
var currentTime = new Date(); //get the current time. //Clock in the time. localStorage.time = currentTime;
当我尝试稍后使用时检索它…
var timeObj = new Date(localStorage.time); var checkInDayOfMonth = timeObj.getUTCDate(); //returns 1-31
timeObj没有正确的日期时间,它似乎有当前时间,好像它忽略了我发送的时间参数。
我正在使用getUTCDate来获取当月的这一天。 如果今天的价值与存储的价值不同,我知道这是新的一天。
打开Google Chrome Inspector会以以下格式显示以localStorage存储的日期:
Wed Dec 11 2013 22:17:45 GMT-0800 (PST)
这不是日期构造函数的可接受格式吗?
如何正确存储和检索localStorage中的日期?
您可以将其作为unix时间戳返回。 确保将数字传递给Date构造函数。
首先,保存。 添加+到new,使其成为时间戳。
localStorage.setItem('time', +new Date);
然后后来检索它,但将数字传递给Date构造函数:
new Date(parseInt(localStorage.getItem('time')));
存储UNIX时间戳,然后从中重新创建日期对象:
window.localStorage.time = new Date().getTime(); var date = new Date(parseInt(window.localStorage.time));
试试这个:
var currentTimeStr = timeObj.getDate() + "-" + (timeObj.getMonth()+1) + "-" + timeObj.getUTCFullYear() + " " + timeObj.getHours() + ":" + timeObj.getMinutes();
它给了我输出:“12-12-2013 13:44”(我在下午1:51检索。所以它没有给出当前时间。)
希望能帮助到你。