2011-01-07 83 views
8

我這樣做:如何在午夜使用Jquery過期Cookie?

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

但它只會第二天到期。

如何在午夜過期cookie?

這個工作會改變嗎?

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

這是很聰明的!我打算使用date.getDate()+ 1,就像下面的答案一樣,但因爲月底結束而感到擔憂。你的午夜是完美的午夜! – 2011-08-14 22:17:46

回答

9

,我認爲這會工作:

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

當您回答時,我正在編輯問題。 THKS – Thiago 2011-01-07 17:07:20

3

據部份的Cookie插件的最新版本(假設這是您所使用的一個:http://plugins.jquery.com/project/Cookie),你可以通過正常的Date對象

我還沒有嘗試過。但該插件的源是相當簡單....

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 
     } 

如果在數通,它假定的天數。如果你傳遞一個日期,那就需要。

0

您可以創建一個JavaScript Date對象今晚(午夜)值,然後設置到期如下:

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

凡日期是日期的對象。

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