I have this JavaScript code:
function spu_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=/";
}
How can I make the cookie expire after 2 hours?
You can extend the life of a cookie beyond the current browser session by setting an expiration date and saving the expiry date within the cookie. This can be done by setting the 'expires' attribute to a date and time.
Just set the expires parameter to a past date: document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; You should define the cookie path to ensure that you delete the right cookie.
To set a cookie so it expires at the end of the browsing session, simply OMIT the expiration parameter altogether. Save this answer.
Cookies can last as long as their creator wants them to. The duration can be set when cookies are created. While session cookies are destroyed when the current browser window is closed, they can also persist for long after the page is closed.
If you want to use the same type of function, transform the days
param into hours
and pass 2
to get a 2 hour expiration date.
function spu_createCookie(name, value, hours)
{
if (hours)
{
var date = new Date();
date.setTime(date.getTime()+(hours*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else
{
var expires = "";
}
document.cookie = name+"="+value+expires+"; path=/";
}
Well -most obvious thing is to make "expire" date +2 hours ? :). Here You have nice prototype for that: Adding hours to Javascript Date object?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With