jquerycookiesjs-cookie

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?


Solution

  • Found the answer in: Frequently-Asked-Questions

    How to make the cookie expire in less than a day?

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