How to expire a Cookie using Jquery at midnight?

后端 未结 4 977
南笙
南笙 2021-01-17 21:56

I did this:

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

But it will only expire next day.

How can I expire a cookie at midnight?

相关标签:
4条回答
  • 2021-01-17 22:25
    var date = new Date();
    var midnight = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59);
    var expires = "expires="+midnight.toGMTString();
    
    0 讨论(0)
  • 2021-01-17 22:27

    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.

    0 讨论(0)
  • 2021-01-17 22:30

    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});
    
    0 讨论(0)
  • 2021-01-17 22:33

    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.

    0 讨论(0)
提交回复
热议问题