Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store Date and Retrieve from Local Storage

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?

like image 573
Joseph Astrahan Avatar asked Dec 12 '13 08:12

Joseph Astrahan


1 Answers

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')));
like image 164
Zlatko Avatar answered Sep 30 '22 17:09

Zlatko