Sometimes, we want to set a cookie with expire time with JavaScript.
In this article, we’ll look at how to set a cookie with expire time with JavaScript.
How to set a cookie with expire time with JavaScript?
To set a cookie with expire time with JavaScript, we can set the expires
value in the cookie.
For instance, we write
const display = () => {
const now = new Date();
const time = now.getTime();
const expireTime = time + 1000 * 36000;
now.setTime(expireTime);
document.cookie = `cookie=ok;expires=${now.toUTCString()};path=/`;
};
to define the display
function.
In it, we set document.cookie
to a string that has the expires
value set to the date string converted from the now
date.
We call toUTCString
to get a UTC date time string.
time
and expireTime
are timestamps in milliseconds
Conclusion
To set a cookie with expire time with JavaScript, we can set the expires
value in the cookie.