I’m trying to set a cross browser expiration date for my cookie by setting both the “expires” and “max-age” options.
Please take a look at my code below to see if there is something wrong with the way I set up my cookie and its expiration date.
let names = JSON.stringify(employees);
let expirationDate = new Date();
//expires in 10 years
expirationDate.setTime(expirationDate.getTime() + 3650 * 24* 60 * 60 * 1000);
let expires = "; expires=" + expirationDate.toUTCString();
//expires in 10 years
let maxAge = "; max-age=" + 3650*24*60*60;
document.cookie = "employeeNames=" + names + maxAge;
I set the cookie to expire in 10 years using both “expires” and “max-age” but when I hover over cookie during debug, it shows the following:
The questions I have are number one can I use both “expires” and “max-age” on a cookie, number 2 is the expiration date supposed to show as part of the cookie, and number 3 why does it say Feb8|2019-07 if it’s supposed to expire 10 years from now.
at what stage do you actually tell the cookie to expire?
No you don’t.
Yes. Browsers that support max-age will use max-age and ignore expires; IE will ignore max-age and use expires, because IE is a silly, silly thing.
What browser are you viewing the cookie in, and what mechanism are you using to do it? Chrome has a nice cookie display section in its settings that will show you the expiry set for your cookie.
2019-07-22T20:33:20 would be nearly the correct time, depending on when you actually set this cookie; 3650 days is not actually quite 10 years, because you’ve forgotten about leap years, but it’s close enough that people probably won’t notice losing a couple of days from the end of their expiry.
though keep in mind max age isnt taking a date, it takes a number of seconds, and then the browser internally applies that number to current timestamp to arrive at expiry.