20

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
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
Attila Naghi
  • 2,535
  • 6
  • 37
  • 59

4 Answers4

43

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
Max Williams
  • 32,435
  • 31
  • 130
  • 197
Felix
  • 37,892
  • 8
  • 43
  • 55
3
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
Satpal
  • 132,252
  • 13
  • 159
  • 168
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
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 });
Butani Vijay
  • 4,181
  • 2
  • 29
  • 61
3

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.

Sebastian Norr
  • 7,686
  • 2
  • 12
  • 17
  • Thanks ... so I want to expire after 1 day. if I write this way is true for 1 day // setcookie("username", "chris", time() + (86400 * 1)); – Amin Jan 17 '20 at 18:16