Javascript 存储日期并从本地存储中检索

Javascript 存储日期并从本地存储中检索,javascript,jquery,html,date,local-storage,Javascript,Jquery,Html,Date,Local Storage,我将日期存储到本地存储,如下所示 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 time

我将日期存储到本地存储,如下所示

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将没有正确的datetime,而是显示当前时间,好像它忽略了我发送的时间的参数

我正在使用getUTCDate获取月份的日期。如果今天的价值与存储中的不同,我知道这是新的一天

打开Google Chrome Inspector将以以下格式显示存储在localStorage中的日期:

Wed Dec 11 2013 22:17:45 GMT-0800 (PST)
这不是日期构造函数可接受的格式吗

如何从localStorage中正确存储和检索日期?

尝试以下方法:

var currentTimeStr = timeObj.getDate() + "-" + (timeObj.getMonth()+1) + "-" + timeObj.getUTCFullYear() + " " + timeObj.getHours() + ":" + timeObj.getMinutes();
它给了我输出:“12-12-2013 13:44”(我在下午1:51检索到了。所以它没有给出当前时间。)


希望有帮助。

存储UNIX时间戳,然后从中重新创建日期对象:

window.localStorage.time = new Date().getTime();

var date = new Date(parseInt(window.localStorage.time));

您可以将其作为unix时间戳取回。确保将数字传递给最新构造函数

首先,保存。将+添加到new,使其成为时间戳

localStorage.setItem('time', +new Date);
然后稍后检索,但将编号传递给最新构造函数:

new Date(parseInt(localStorage.getItem('time')));

我试着这么做,但我刚回来。我看到了UNIX时间戳(一长串数字)。它似乎无法正确地从中创建日期对象。有什么想法吗?你真的测试过这个想法吗?我想我的评论看起来是错误的,我的意思是说我真的很喜欢这个想法(如果它能奏效的话)。有时人们发布伪代码。所以我很好奇你是在做什么,还是你已经尝试过这个想法,并且它确实有效?检索部分需要一个parseInt。看看我的答案?上面的答案有一个错误,是在月的前一天,也是月的前一天,你需要说+1,因为它返回0-11@JosephAstrahan许多人不会认为这是一个错误;如果你挑剔的话,应该是YYYY-MM-DD。我几年前就写了这条评论,哈哈,我同意你现在所说的