Setting a cookie to expire in javascript

cookietimeAdding and setting a cookie via javascript is pretty simple. Sometimes you want the cookie to expire in a certain amount of time, below is the method is use to calculate an expiration:

//create a date object
var date = new Date();
//add the current date + some seconds 
//(below I add 300 seconds or 5 minutes). 
//The 1000 is milliseconds
 date.setTime(date.getTime() + (300 * 1000));
//convert the future date to universal time
var expires = date.toUTCString();
//set the cookie using whatever method / function you choose.
setCookie('cookiename', 'cookievalue', expires);

For the fun of it, below is the function I use to set cookies:

function setCookie(cname, cvalue, expires) {
 document.cookie = cname + "=" + escape(cvalue) +
 ((expires) ? "; expires=" + expires : "");
}

And since we’re talking about cookies, here is a collection of great cookies recipes you can actually eat!

Setting a cookie to expire in javascript

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s