簡體   English   中英

存儲日期並從本地存儲中檢索

[英]Store Date and Retrieve from 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 

timeObj將沒有正確的日期時間,而是顯示當前時間,好像它忽略了我發送的時間參數。

我正在使用getUTCDate來獲取當月的這一天。 如果今天的價值與存儲的價值不同,我知道這是新的一天。

打開Goog​​le 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檢索。所以它沒有給出當前時間。)

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM