Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a JavaScript cookie to expire in 10 years?

Tags:

javascript

The function I'm using sets the cookie expiration in this part of the code:

time += 3600 * 1000;

It expires in an hour. How to set this to expire in 10 years?

like image 421
Jake Avatar asked Jun 14 '11 18:06

Jake


People also ask

How do I set cookie expiry time?

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 long do js cookies last?

Persistent cookies are not deleted by the browser when the user closes it. These cookies have an expiration date that you can set in your server. You can set a cookie to expire in a day or ten years.

How do you set a cookie for one year?

php setcookie("TestName", "Test Value", time()+3600 * 24 * 365); ?> >> Here 'TestName' is name of cookie. >> "Test Value" is value to store. >> time()+3600 * 24 * 365 - will set cookie time till 1 year.

How do you set cookies to expire in 30 days?

Or you might use mktime(). time()+60*60*24*30 will set the cookie to expire in 30 days. If not set, the cookie will expire at the end of the session (when the browser closes). The path on the server in which the cookie will be available on.


1 Answers

Note: toGMTString() is deprecated since Jun 23, 2017, 9:04:01 AM and should no longer be used. It remains implemented only for backward compatibility; please use toUTCString() instead.

For more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toGMTString

var CookieDate = new Date;
CookieDate.setFullYear(CookieDate.getFullYear() +10);
document.cookie = 'myCookie=to_be_deleted; expires=' + CookieDate.toGMTString() + ';';

You can still achieve the same result just by replacing toGMTString() with toUTCString() as so:

 var CookieDate = new Date;
    CookieDate.setFullYear(CookieDate.getFullYear() +10);
    document.cookie = 'myCookie=to_be_deleted; expires=' + CookieDate.toUTCString() + ';';
like image 72
Rafael Herscovici Avatar answered Sep 22 '22 18:09

Rafael Herscovici