6

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?

Joseph Astrahan
  • 8,659
  • 12
  • 83
  • 154

3 Answers3

14

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')));
Zlatko
  • 18,936
  • 14
  • 70
  • 123
3

Store the UNIX timestamp and then recreate the date object from that:

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

var date = new Date(parseInt(window.localStorage.time));
TMan
  • 1,775
  • 1
  • 14
  • 26
  • I tried doing this but I just get back NaN. I see the UNIX timestamp (the long series of numbers). It just won't seem to create the date object from it correctly. Any ideas? Did you actually test this idea? – Joseph Astrahan Dec 12 '13 at 19:00
  • I think my comment came out looking wrong, I meant to say I really like this idea (if it will work). Sometimes people post pseudo code. So was curious if that is what you were doing or if you have tried this idea and it verifiably worked? – Joseph Astrahan Dec 12 '13 at 19:08
  • 1
    The retreival part needs a parseInt. Look at my answer? – Zlatko Dec 13 '13 at 04:17
0

Try this:

var currentTimeStr = timeObj.getDate() + "-" + (timeObj.getMonth()+1) + "-" + timeObj.getUTCFullYear() + " " + timeObj.getHours() + ":" + timeObj.getMinutes();

It gave me output: "12-12-2013 13:44" (I retrieved at 1:51 PM. So its not giving current time.)

Hope it helps.

MysticMagicϡ
  • 28,593
  • 16
  • 73
  • 124