Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a cookie expire after 2 hours

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?

like image 532
Tureac Cosmin Avatar asked Sep 28 '13 15:09

Tureac Cosmin


People also ask

Can you set an expiration date and time for a cookie?

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.

How do I set cookie expiry 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.

How do I set cookies to expire at end of session?

To set a cookie so it expires at the end of the browsing session, simply OMIT the expiration parameter altogether. Save this answer.

How long is a cookie valid?

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.


2 Answers

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=/";
}
like image 185
Sébastien Avatar answered Nov 01 '22 18:11

Sébastien


Well -most obvious thing is to make "expire" date +2 hours ? :). Here You have nice prototype for that: Adding hours to Javascript Date object?

like image 20
masahuku Avatar answered Nov 01 '22 17:11

masahuku