8

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});
Flexo
  • 87,323
  • 22
  • 191
  • 272
Thiago
  • 1,547
  • 3
  • 25
  • 40
  • this is very smart! I was going to use date.getDate()+1 just like was answered below but was concerned because end of the month. Your midnight is the perfect midnight! – Devin Rhode Aug 14 '11 at 22:17

4 Answers4

10

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});
Adam Prax
  • 6,413
  • 3
  • 30
  • 31
3

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.

Mike Ruhlin
  • 3,546
  • 2
  • 21
  • 31
1
var date = new Date();
var midnight = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59);
var expires = "expires="+midnight.toGMTString();
M Arfan
  • 4,384
  • 4
  • 29
  • 46
0

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.

diagonalbatman
  • 17,340
  • 3
  • 31
  • 31