How to expire a cookie in 30 minutes using jQuery?

JavascriptJqueryCookies

Javascript Problem Overview


How to Expire a Cookie in 30 min ? I am using a jQuery cookie. I am able to do something like this.

$.cookie("example", "foo", { expires: 1 });

This is for 1 day. But how can we set expiry time to 30 min.

Javascript Solutions


Solution 1 - Javascript

30 minutes is 30 * 60 * 1000 miliseconds. Add that to the current date to specify an expiration date 30 minutes in the future.

 var date = new Date();
 var minutes = 30;
 date.setTime(date.getTime() + (minutes * 60 * 1000));
 $.cookie("example", "foo", { expires: date });

Solution 2 - Javascript

If you're using jQuery Cookie (https://plugins.jquery.com/cookie/), you can use decimal point or fractions.

As one day is 1, one minute would be 1 / 1440 (there's 1440 minutes in a day).

So 30 minutes is 30 / 1440 = 0.02083333.

Final code:

$.cookie("example", "foo", { expires: 30 / 1440, path: '/' });

I've added path: '/' so that you don't forget that the cookie is set on the current path. If you're on /my-directory/ the cookie is only set for this very directory.

Solution 3 - Javascript

I had issues getting the above code to work within cookie.js. The following code managed to create the correct timestamp for the cookie expiration in my instance.

var inFifteenMinutes = new Date(new Date().getTime() + 15 * 60 * 1000);

This was from the FAQs for Cookie.js

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionbluwater2001View Question on Stackoverflow
Solution 1 - JavascriptSinan ÜnürView Answer on Stackoverflow
Solution 2 - JavascriptYvanView Answer on Stackoverflow
Solution 3 - JavascriptTerry CarterView Answer on Stackoverflow