本文介绍了存储日期并从本地存储检索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



JS:

  var currentTime = new Date(); //获取当前时间

//当时钟。
localStorage.time = currentTime;

当我尝试在稍后使用...

  var timeObj = new Date(localStorage.time); 
var checkInDayOfMonth = timeObj.getUTCDate(); //返回1-31

timeObj将不会有正确的日期时间,它似乎有当前的时间,好像它忽略了我发送的时间的参数。



我正在使用getUTCDate来获取一个月的日子。如果今天的价值不同于储存空间,我知道这是一个新的一天。



打开Goog​​le Chrome浏览器会显示本地存储在本地的日期格式:

  Wed Dec 11 2013 22:17:45 GMT-0800(PST)

这个日期构造函数是不是可接受的格式?



我如何存储并从localStorage正确地检索日期?

解决方案

您可以将其恢复为unix时间戳。确保将数字传递给Date构造函数。



首先,保存。添加一个+到新的,以使其成为时间戳。

  localStorage.setItem('time',+ new Date); 

然后再调用它,但将数字传递给Date构造函数:

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


I stored a date to local storage like below.

JS:

var currentTime = new Date(); //get the current time.

//Clock in the time.
localStorage.time = currentTime;

When I try to retrieve it sometime later using...

var timeObj = new Date(localStorage.time);
var checkInDayOfMonth = timeObj.getUTCDate(); //returns 1-31

the timeObj will not have the correct datetime, it instead appears to have the current time as if it's ignoring the parameters of the time I'm sending.

I'm using getUTCDate to get the day of the month. If the value of today is different than what is in storage I know it's a new day.

Opening Google Chrome Inspector reveals the date stored in localStorage in this format:

Wed Dec 11 2013 22:17:45 GMT-0800 (PST)

Is that not an acceptable format for the date constructor?

How can I store and retreive dates from localStorage correctly?

解决方案

You can get it back as unix timestamp. Make sure to pass a number to Date constructor.

First, save. Add a + to new, to make this a timestamp.

localStorage.setItem('time', +new Date);

Then later retreive it, but pass the number to Date constructor:

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

这篇关于存储日期并从本地存储检索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 13:15
查看更多