Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a cookie to expire in 1 hour in Javascript?

Tags:

javascript

People also ask

How do you set cookies for one hour?

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 you make cookies expire immediately?

To easily delete any cookie, simply set its expiration date as the epoch timestamp: document. cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/"; document.

How do you set cookie lifetime?

setcookie( "CookieName", "CookieValue", time() + (10 * 365 * 24 * 60 * 60) ); Note that if you set a date past 2038 in 32-bit PHP, the number will wrap around and you'll get a cookie that expires instantly.

How long do cookies last JavaScript?

Just a note that any dates beyond January 2038 will doomed you for the cookies (32-bit int) will be deleted instantly.


Code :

var now = new Date();
var time = now.getTime();
time += 3600 * 1000;
now.setTime(time);
document.cookie = 
'username=' + value + 
'; expires=' + now.toUTCString() + 
'; path=/';

You can write this in a more compact way:

var now = new Date();
now.setTime(now.getTime() + 1 * 3600 * 1000);
document.cookie = "name=value; expires=" + now.toUTCString() + "; path=/";

And for someone like me, who wasted an hour trying to figure out why the cookie with expiration is not set up (but without expiration can be set up) in Chrome, here is in answer:

For some strange reason Chrome team decided to ignore cookies from local pages. So if you do this on localhost, you will not be able to see your cookie in Chrome. So either upload it on the server or use another browser.


Instead of using expires, you can use max-age. Max-Age takes presence over expires and accepts an expiration duration in seconds.

For your example, considering an hour is 3600 seconds, the code would be:

document.cookie = 'username=' + value + '; max-age=3600; path=/';