JavaScript Cookies Expires
JavaScript Cookies Expires
The expires
parameter tells the browser when to delete the cookie
Cookie Expires Not Specified
When expires
parameter is not specified, by default the browser will store the cookie with the expiration of 1 year.
Example
<!DOCTYPE html>
<html>
<body>
<script>
var name = "Steve";
document.cookie = "username="+name+";path=/";
document.write("Cookie written");
</script>
</body>
</html>
Cookie Expires at Specific Time
You can also add an expiry date in UTC.
Example
<!DOCTYPE html>
<html>
<body>
<script>
var name = "Steve";
document.cookie = "username="+name+";expires=Thu, 30 Dec 2021 12:00:00 UTC;path=/";
document.write("Cookie written");
</script>
</body>
</html>
Cookie Expires After One Hour
In the following example, the cookies will be deleted after one hour.
Example
<!DOCTYPE html>
<html>
<body>
<script>
var weight = "80 kg";
//one hour = 3600 = 60 * 60 * 1000= (seconds * minutes * milliseconds)
var oneHour = 3600 * 1000;
//Current Date
var now = new Date();
//Current Time in milliseconds
var time = now.getTime();
//Add One hour
time += oneHour;
//Set current time, one hour after
now.setTime(time);
document.cookie = "userweight="+weight+";expires="+now.toUTCString()+";path=/";
document.write("Cookie written");
</script>
</body>
</html>
Cookie Delete
To delete a cookie immediately, set the expires date to something in the past.
Example
<!DOCTYPE html>
<html>
<body>
<script>
var name = "Steve";
document.cookie = "username="+name+";path=/";
document.cookie = "username="+name+";expires=Thu, 30 Dec 1999 12:00:00 UTC;path=/";
document.write("Cookie written");
</script>
</body>
</html>
Reminder
Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.
We are working to cover every Single Concept in JavaScript.
Please do google search for:
Join Our Channel
Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.
This channel is primarily useful for Full Stack Web Developer.
Share this Page
Meet the Author