Dav*_*igh 40 javascript cookies
我正在使用一个设置cookie的函数.此功能允许将cookie名称,cookie值和cookie的额外到期日期传递给它.
功能:
function setCookie(name, value, exdate) {
var c_value = escape(value) + ((exdate === null || exdate === undefined) ? "" : "; expires=" + exdate);
document.cookie = name + "=" + c_value;
};
Run Code Online (Sandbox Code Playgroud)
用法:
setCookie("my-cookie-name","my-value","Sun, 15 Jul 2012 00:00:01 GMT");
Run Code Online (Sandbox Code Playgroud)
我已经使用了上面的日期格式的功能,并认为它是跨浏览器兼容的,因为我已经测试过,如果cookie在关闭各种浏览器并重新打开后仍然存在.我发现使用像这样的格式时会出现问题"15 Jul 2012".这种格式在firefox的开发过程中适用于我,但其他浏览器似乎只将cookie设置为会话cookie.
我应该坚持使用这种格式:"Sun,2012年7月15日00:00:01格林威治标准时间"或者是否有其他格式我可以使用的有效期限将适用于主流浏览器(IE 7-9,Firefox,Chrome) ,Opera,Safari)?
编辑/ UPDATE:
Cookie要求到期日期为UTC/GMT格式(请参阅下面的答案).
我已将我的功能编辑为以下内容,以便转换任何不是核心格式的日期.
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;
};
Run Code Online (Sandbox Code Playgroud)
Dav*_*igh 37
根据测试并进一步阅读此内容,Cookie需要UTC/GMT格式的日期,例如Sun,2012年7月15日00:00:01 GMT
因此,在其它的格式,如任何日期2012年7月15日,或15 /月/ 2012,或07月15日,必须作为一个传递new Date对象,然后通过toUTCString()或toGMTString()功能.
因此我将我的功能编辑为以下内容:
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;
};
Run Code Online (Sandbox Code Playgroud)
rfc 6265 中指定的用于生成 Set-Cookie 标头的语法使用
rfc1123-date = wkday "," SP date1 SP time SP "GMT"cookie 日期格式,因此"Sun, 15 Jul 2012 00:00:01 GMT"有效。
如果我理解正确,解析算法会识别其他格式,例如: 00:00:01 15 jul 2012但不应生成它们。