简体   繁体   中英

Javascript: Make a cookie expire in 5 minutes

Could someone update the following code to make the cookie expire in 5 minutes.

function createCookie(name,value,days) {
if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";

}

Just edit the time argument to take minutes instead of days

function createCookie(name,value,minutes) {
    if (minutes) {
        var date = new Date();
        date.setTime(date.getTime()+(minutes*60*1000));
        var expires = "; expires="+date.toGMTString();
    } else {
        var expires = "";
    }
    document.cookie = name+"="+value+expires+"; path=/";
}

createCookie("name", "value", 5)
date.setTime(date.getTime()+(days*5*60*1000));

Explanation:

The previous code was this:

date.setTime(date.getTime()+(days*24*60*60*1000));

days is presumably the number of days, and then it's multiplied by 24 hours in a day, 60 minutes in an hour, 60 seconds in a minute, and 1000 milliseconds in a second.

So days*24*60 was the number of minutes. Just put a 5 in there instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM