0

My code to set local storage like this :

var now = new Date();
now.setHours(now.getHours() + 1);
var cacheData = {data: data, expired: now}
localStorage.setItem('storedData', JSON.stringify(cacheData))

My code to check expired or no like this :

var object = JSON.parse(localStorage.getItem("storedData")),
    expired = object.expired,
    now = new Date()

if(now > expired) {
    console.log('cache dihapus')
    localStorage.removeItem("storedData");
}

After 1 hour, I run the script, but the local storage not remodev

Why it not removed?

The result of console.log(now) and console.log(expired) like this :

Wed Aug 09 2017 17:41:13 GMT+0700 (Russia TZ 6 Standard Time)

2017-08-09T10:29:21.933Z

Seems the format different. Maybe its a problem there

moses toh
  • 12,344
  • 71
  • 243
  • 443
  • Possible duplicate of [How to parse JSON to receive a Date object in JavaScript?](https://stackoverflow.com/questions/4511705/how-to-parse-json-to-receive-a-date-object-in-javascript) – Aaron Aug 09 '17 at 10:54

3 Answers3

1

expired is in JSON format (for Date). Better, you convert 'now' to the same format by using,

now = new Date()
now = now.toJSON()

You can compare 'now' and 'expired' by using > or < or ==, etc.

Chaitanya Mankala
  • 1,594
  • 17
  • 24
0

If you are going to compare with > < = you should run it on the getTime() of a Date object.

So construct two dates with the strings you have and then compare them as such: if(now.getTime() > expired.getTime())

I'm afraid at the moment you are comparing a String with a Date object.

Airwavezx
  • 323
  • 1
  • 9
0

JSON does not support Date objects, so when you JSON.stringify your data to put it into LocalStorage, the dates get flattened into strings.

To turn them back into proper Date objects, pass them to the Date constructor (e.g. new Date(yourString);), or use a library like Moment.js.

Joe Clay
  • 33,401
  • 4
  • 85
  • 85