Reputation: 83
I have this JavaScript code:
function spu_createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else
var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
How can I make the cookie expire after 2 hours?
Upvotes: 7
Views: 35296
Reputation: 11
The following one-liner will set a cookie, name
, with the value, value
, and an expiration of two hours from the time of its creation. If the optional argument, days
, is supplied, the cookie will expire after that many days instead.
Warning: there is no error-checking, so if mandatory parameters are omitted when called, or arguments are mistyped, the function will throw an error.
spu_createCookie = (name, value, days) => { document.cookie = `${name}=${value}; expires=${new Date(Date.now() + (days ? 86400000 * days : 7200000)).toGMTString()}; path=/` }
Relevant JavaScript syntax concepts:
An arrow function expression is a compact alternative to a traditional function expression, but is limited and can't be used in all situations.
Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.
The conditional (ternary) operator is the only JavaScript operator that takes three operands ... This operator is frequently used as a shortcut for the if statement.
Upvotes: 1
Reputation: 1259
Try this:
function writeCookie (key, value, hours) {
var date = new Date();
// Get milliseconds at current time plus number of hours*60 minutes*60 seconds* 1000 milliseconds
date.setTime(+ date + (hours * 3600000)); //60 * 60 * 1000
window.document.cookie = key + "=" + value + "; expires=" + date.toGMTString() + "; path=/";
return value;
};
Usage:
<script>
writeCookie ("myCookie", "12345", 24);
</script>
//for 24 hours
Upvotes: 5
Reputation: 12139
If you want to use the same type of function, transform the days
param into hours
and pass 2
to get a 2 hour expiration date.
function spu_createCookie(name, value, hours)
{
if (hours)
{
var date = new Date();
date.setTime(date.getTime()+(hours*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else
{
var expires = "";
}
document.cookie = name+"="+value+expires+"; path=/";
}
Upvotes: 10
Reputation: 246
This would do it.
var now = new Date();
var time = now.getTime();
time += 7200 * 1000;
now.setTime(time);
document.cookie =
name+ '=' + value +
'; expires=' + now.toGMTString() +
'; path=/';
Upvotes: 0
Reputation: 184
Well -most obvious thing is to make "expire" date +2 hours ? :). Here You have nice prototype for that: Adding hours to Javascript Date object?
Upvotes: 5