根据时间戳删除localStorage记录

时间:2015-02-10 14:50:52

标签: javascript jquery local-storage

我有一个名为 homeCookie 的localStorage记录及其内容: Value1 | 1423415640 | Value3 |值3

我需要通过jQuery删除它,如果它比时间戳 时间戳 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];

任何人都可以帮助我完成任务吗?如果时间戳早于现在,则删除整个 homeCookie 记录。

3 个答案:

答案 0 :(得分:1)

您可以在添加值

时添加时间
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);
}

答案 1 :(得分:1)

这不会起作用吗?

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

答案 2 :(得分:1)

这可以帮到你:

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");   
}