Doug Fir
Doug Fir

Reputation: 21322

cookie not setting as expected

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?

Upvotes: 0

Views: 36

Answers (2)

Rico Herwig
Rico Herwig

Reputation: 1712

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();

Upvotes: 1

mfreitas
mfreitas

Reputation: 2405

this will work:

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

Upvotes: 1

Related Questions