cookie not setting as expected

36 Views Asked by At

When I set a cookie like this, it works:

var now = new Date();
now.setDate(now.getDate() + 30);
document.cookie='bla=cats; expires=' + now + ';path=/;'

But when I do this it does not:

var now = new Date();
now.setMinutes(now.getMinutes() + 30); 
document.cookie='bla=cats; expires=' + now + ';path=/;'

So I want to set a cookie with 30 mins expiration, not 30 days. 30 days works fine, the latter one does not. Why? How can I set a 30 min cookie?

2

There are 2 best solutions below

1
Rico Herwig On BEST ANSWER

You can either try:

now.setTime(now.getTime() + (30*60*1000));

And/or converting your Date-object into a time-string afterwards, by doing

var expires = now.toGMTString();
2
mfreitas On

this will work:

var now = new Date();
now.setTime(now.getTime() + (30 * 60 * 1000));
document.cookie='bla=cats; expires=' + now + ';path=/;'