2
 $localStorage.doctorDateTime.push({                            
    fullDate : new Date(doctorDateTime)
    });

I passed date string in new Date and then save it to local storage but when i retrieve it from local storage it showing me this format:

2015-01-01T13:41:18.300Z

while if console.log(doctorDateTime). it is showing right date string

4

3 回答 3

4

localStorage stored data are strings only. If you are trying to store something that is not string type, an implicit type coercion is taken place.

However, it looks like depending on some lib implementation you are using, because what you got behaves like Date.prototype.toISOString(), while following code behaves like Date.prototype.toString():

localStorage.setItem("fullDate", new Date(doctorDateTime));

You'd better explicitly convert the Date object to a string in your desired format before set to localStorage.

But, you could still get the Date object back with the ISO time string:

var str = '2015-01-01T13:41:18.300Z';
var time = new Date(str); // you got the object back!
于 2015-01-01T13:59:57.267 回答
2

That's what happens when you do ( new Date() ).toString(), it's the string representation of the date as it's converted to a string when stored in Local Storage.

Store the timestamp instead, it's a number representing milliseconds from epoch, and not an object

$localStorage.doctorDateTime.push({                            
    fullDate : ( new Date(doctorDateTime) ).getTime()
});

Local Storage's functionality is limited to handle only string key/value pairs.
Some browser will store objects, but it's not something you can rely on, you should be storing strings. The easiest would be to store the timestamp, and then run that timestamp through new Date when you get it from Local Storage to get a date object.

于 2015-01-01T13:58:15.217 回答
0

If you pass object to localstorage it will first do JSON.stringify of your object and then store it to local storage. So when next time you retrieve it, it will give you string value of date object. Try to do JSON.stringify(new Date()) you will have your date string. This is same string you are getting when you fetch next time.

Best solution is convert your date to timestap when you store it to local storage. And convert it to Date object when you are fetching from local storage.

LocalStorage only supports text. So it will always do JSON.stringify on your object before storing it.

于 2015-01-01T14:04:18.193 回答