ConfusedDeer
ConfusedDeer

Reputation: 3415

jscookie.js how to expire cookie in minutes not days?

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?

Upvotes: 5

Views: 14322

Answers (3)

Uzbekjon
Uzbekjon

Reputation: 11813

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

Upvotes: 1

ConfusedDeer
ConfusedDeer

Reputation: 3415

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

Upvotes: 10

Steve Danner
Steve Danner

Reputation: 22158

You can just divide by the minutes in a day.

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

Upvotes: 3

Related Questions