Which date formats can I use when specifying the expiry date when setting a cookie?

JavascriptCookies

Javascript Problem Overview


I am using a function which sets a cookie. This function allows the cookie name, the cookie value and an additional expiry date of the cookie to be passed into it.

function setCookie(name, value, exdate) {
	var c_value = escape(value) + 
      ((exdate === null || exdate === undefined) ? "" : "; expires=" + exdate);
	document.cookie = name + "=" + c_value;
};

Usage:

setCookie("my-cookie-name","my-value","Sun, 15 Jul 2012 00:00:01 GMT");

I have used the function with the date format above and believe it is cross browser compatible as I have tested if the cookie remains after closing various browsers and reopening them. I discovered that there were problems when using a format like "15 Jul 2012". This format worked for me during development in Firefox, but other browsers only seemed to set the cookie as a session cookie.

Should I stick to using just this format: "Sun, 15 Jul 2012 00:00:01 GMT" or are there other formats I could use for the expiry date that will work across the major browsers (IE 7-9, Firefox, Chrome, Opera, Safari)?

Javascript Solutions


Solution 1 - Javascript

Based on testing and further reading into this, a date in a UTC/GMT format is required by cookies e.g. Sun, 15 Jul 2012 00:00:01 GMT

Therefore any dates in other formats such as 15 Jul 2012, or 15/Jul/2012, or 07/15/2012, have to be passed as a new Date object and then through the toUTCString() or the toGMTString() function.

therefore I have edited my function to the following:

function setCookie(name, value, exdate) {
    //If exdate exists then pass it as a new Date and convert to UTC format
    (exdate) && (exdate = new Date(exdate).toUTCString());
    var c_value = escape(value) + ((exdate === null || exdate === undefined) ? "" : "; expires=" + exdate);
    document.cookie = name + "=" + c_value;
};

Solution 2 - Javascript

The syntax specified in rfc 6265 for generating Set-Cookie headers uses
rfc1123-date = wkday "," SP date1 SP time SP "GMT" cookie date format and therefore "Sun, 15 Jul 2012 00:00:01 GMT" works.

If I understand it correctly, the parsing algorithm would recognize other formats e.g.: 00:00:01 15 jul 2012 but they should not be generated.

Solution 3 - Javascript

Found the date format ddd, dd MMM yyyy HH':'mm':'ss 'GMT'. May someone find is useful. Also very good reference here

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDave HaighView Question on Stackoverflow
Solution 1 - JavascriptDave HaighView Answer on Stackoverflow
Solution 2 - JavascriptjfsView Answer on Stackoverflow
Solution 3 - JavascriptChinthaka DevindaView Answer on Stackoverflow