Thiago
Thiago

Reputation: 1565

How to expire a Cookie using Jquery at midnight?

I did this:

$.cookie("ultOS", (i), {expires:1});

But it will only expire next day.

How can I expire a cookie at midnight?

Would this work instead?

var date = new Date();
var midnight = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59);
$.cookie("ultOS", (i), {expires: midnight});

Upvotes: 8

Views: 6582

Answers (4)

M Arfan
M Arfan

Reputation: 4575

var date = new Date();
var midnight = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59);
var expires = "expires="+midnight.toGMTString();

Upvotes: 1

user463535
user463535

Reputation:

I think this would work:

var currentDate = new Date();
expirationDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate()+1, 0, 0, 0);
$.cookie("ultOS", "5", {expires: expirationDate});

Upvotes: 10

diagonalbatman
diagonalbatman

Reputation: 18002

You can create a Javascript Date object with tonights (midnight) value, then set the expiration as follows:

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

Where date is the date object.

Upvotes: 0

Mike Ruhlin
Mike Ruhlin

Reputation: 3556

According to the latest version of ths cookie plugin (assuming this is the one you're using: http://plugins.jquery.com/project/Cookie), you can pass a normal Date object in.

I haven't tried it, but the source of the plugin is fairly straightforward....

if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }

If you pass in a number, it assumes that's number of days. If you pass in a Date, it takes that.

Upvotes: 3

Related Questions