0

I have a date stored in localStorage under the variable deadline (Tue Jul 05 2016 18:15:00 GMT+0100 (BST)) and I want to find the difference between this date and new Date() however any function I try to carry out with the locally stored date doesn't seem to work.

For example if I try to carry out: console.log(deadline.getTime()) I get the error: deadline.getTime is not a function but when I carry out the same function on the new Date() it works fine despite the syntax of the dates being exactly the same. Can anybody shed some light? Thanks.

mellows
  • 303
  • 1
  • 7
  • 27

1 Answers1

4

All values in localStorage are always strings. When you saving Date object in localStorage it converts to automatically string.

So when you getting back your deadline it's not Date, it it's string representation. If you want to call Date methods, then you need to convert string representation to Date. There is library (moment.js) that can help you.

Also there is easer way to get your date back. Just don't save it as default string representation. Save it as timestamp. Then, when you need to retrive date, create new Date from timestamp in localStorage.

//save in localStorage
localStorage.setItem( 'deadline', deadline_date.getTime() );

//load from localStorage
var deadline = new Date( localStorage.getItem( 'deadline' ) );
Arnial
  • 1,433
  • 1
  • 11
  • 10