How do I set a cookie to expire after 1 minute or 30 seconds in Jquery?

末鹿安然 提交于 2019-12-08 15:00:59

问题


How do i set my cookie to expire after 30 sec or 1 m ? this is my code :

$.cookie('username', username, { expires: 14 });  // expires after 14 days

回答1:


For 1 minute, you can use:

var date = new Date();
date.setTime(date.getTime() + (60 * 1000));
$.cookie('username', username, { expires: date });  // expires after 1 minute

For 30 seconds, you can use:

var date = new Date();
date.setTime(date.getTime() + (30 * 1000));
$.cookie('username', username, { expires: date });  // expires after 30 second



回答2:


var date = new Date();
date.setTime(date.getTime() + (30 * 1000)); //add 30s to current date-time 1s = 1000ms
$.cookie('username', username, { expires: date });  //set it expiry



回答3:


You can Use as below for 1 minute and 30 seconds:

 var date = new Date();
 var minutes = 1.5;
 date.setTime(date.getTime() + (minutes * 60 * 1000));
 $.cookie('username', username, { expires: date });

//3.5* 60 * 1000 = 1 minute and 30 seconds

//For 30 Seconds

  var date = new Date();
 var minutes = 0.5;
 date.setTime(date.getTime() + (minutes * 60 * 1000));
 $.cookie('username', username, { expires: date });



回答4:


Source: http://www.informit.com/articles/article.aspx?p=24592&seqNum=3

Quote:

You need to create the expiration date in seconds—not only that, but it has to be in seconds since January 1, 1970. You may wonder how you are going to figure out your expiration dates when you have to determine them in regard to January 1, 1970. This is where the time() function comes in.

The time() function returns the number of seconds since January 1, 1970. If you want to create a cookie that expires in 30 days, you need to do the following:

  • Get the number of seconds since 1970.

  • Determine the number of seconds that you want the cookie to last.

  • Add the number of seconds since 1970 to the number of seconds that you want the cookie to last.

Because we know that there are 86,400 seconds in a day (60 seconds x 60 minutes x 24 hours), you could create a cookie that expires in 30 days, like this:

setcookie("username", "chris", time() + (86400 * 30));

This function places a cookie on the user's browser for 30 days. Anytime during those 30 days, you can access the variable $username from within the script and it will return (in the above example) chris.



来源:https://stackoverflow.com/questions/22371826/how-do-i-set-a-cookie-to-expire-after-1-minute-or-30-seconds-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!