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

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

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

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