5

I'm using this jquery cookie named jscookie.js and I've read over the readme and even implemented into my project.

The readme explains how to expire a cookie in 'days', but not hours or minutes.

Create a cookie that expires 7 days from now, valid across the entire site:

Cookies.set('name', 'value', { expires: 7 });

How do I set a cookie to expire in minutes or hours?

ConfusedDeer
  • 3,335
  • 8
  • 44
  • 72
  • The wiki addresses this, which is a pretty common question: https://github.com/js-cookie/js-cookie/wiki/Frequently-Asked-Questions#expire-cookies-in-less-than-a-day – Fagner Brack May 26 '16 at 23:27

3 Answers3

10

Found the answer in: Frequently-Asked-Questions

JavaScript Cookie supports a Date instance to be passed in the expires attribute. That provides a lot of flexibility since a Date instance can specify any moment in time.

Take for example, when you want the cookie to expire 15 minutes from now:

var inFifteenMinutes = new Date(new Date().getTime() + 15 * 60 * 1000);
Cookies.set('foo', 'bar', {
    expires: inFifteenMinutes
});

Also, you can specify fractions to expire in half a day (12 hours):

Cookies.set('foo', 'bar', {
    expires: 0.5
});

Or in 30 minutes:

Cookies.set('foo', 'bar', {
    expires: 1/48
});
ConfusedDeer
  • 3,335
  • 8
  • 44
  • 72
  • I would suggest at least linking to the anchor, because the Wiki will change and the content might stay out of view. – Fagner Brack May 26 '16 at 23:28
3

You can just divide by the minutes in a day.

Cookies.set('name','value', {expires: (1 / 1440) * minutes });

Steve Danner
  • 21,818
  • 7
  • 41
  • 51
1

Give it an instance of Date object with the date when you want your cookie to expire:

// Time in the future
var expire = Date.now();

// Add period in minutes
expire.setMinutes(expire.getMinutes() + 40);

// Add period in hours
expire.setHours(expire.getHours() + 3);

Cookies.set('name', 'value', { expires: expire});
Uzbekjon
  • 11,655
  • 3
  • 37
  • 54