Pregunta

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
¿Fue útil?

Solución

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

Otros consejos

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

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 });

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top