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

Javascript

Javascript Problem Overview


How to set this cookie to expire in one hour from the current time:

document.cookie = 'username=' + value; + 'expires=' + WHAT GOES HERE?; + 'path = /';

Javascript Solutions


Solution 1 - Javascript

Code :

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

Solution 2 - Javascript

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.

Solution 3 - Javascript

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=/';

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaveView Question on Stackoverflow
Solution 1 - JavascriptDarin DimitrovView Answer on Stackoverflow
Solution 2 - JavascriptSalvador DaliView Answer on Stackoverflow
Solution 3 - JavascriptsplchView Answer on Stackoverflow