根据时间戳删除 localStorage 记录

Delete a localStorage record based on its timestamp

我有一个名为 homeCookie 的 localStorage 记录,它的内容是:Value1 | 1423415640 |值 3 |值 3

我需要按 jQuery 删除它,如果它比 timestamp 更旧,即 1423415640

要获取其值,我使用以下代码:

var values = window.localStorage.getItem('homeCookie');
values = values.split('|');
window.opt1 = values[0];
window.opt2 = values[1];
window.opt3 = values[2];
window.opt4 = values[3];

谁能帮我完成任务?如果 timestamp 早于 now.

,则删除整个 homeCookie 记录

您可以在添加值的那一刻添加时间

var home = 'homeCookie',
    currentTime = new Date();

localStorage.setItem(home + 'time' , currentTime);

稍后在检索所有内容时

var values, 
clock = window.localStorage.getItem(home + 'time');

if(outOfTime(clock){
     localStorage.removeItem(home);
} else {
    values = window.localStorage.getItem(home);
}

这不行吗?

if(new Date().getTime() > parseFloat(window.opt2))
    window.localStorage.removeItem('homeCookie')

这可以帮助你:

var object = {value: "value1", timestamp: '1423415640'};

localStorage.setItem("homeCookie", JSON.stringify(object)); //save Object as json-string

var values = JSON.parse(localStorage.getItem("homeCookie")), //parse json-data from localStorage
    expiration = values.timestamp, //get timestamp from "localStorage"-object
    now = new Date().getTime().toString(); //get current timestamp as string

if(now > expiration){
    localStorage.removeItem("homeCookie");   
}