今天碰到一个需要设置cookies当天23:59:59时失效的效果,此方法可以实现。
//添加cookie
var setCookie = function (c_name, value) {
var curDate = new Date();
//当前时间戳
var curTamp = curDate.getTime();
//当日凌晨的时间戳,减去一毫秒是为了防止后续得到的时间不会达到00:00:00的状态
var curWeeHours = new Date(curDate.toLocaleDateString()).getTime() - 1;
//当日已经过去的时间(毫秒)
var passedTamp = curTamp - curWeeHours;
//当日剩余时间
var leftTamp = 24 * 60 * 60 * 1000 - passedTamp;
var leftTime = new Date();
leftTime.setTime(leftTamp + curTamp);
//创建cookie
document.cookie = c_name + "=" + escape(value) + ";expires=" + leftTime.toGMTString();
}
//获取cookie
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=")
if (c_start != -1) {
c_start = c_start + c_name.length + 1
c_end = document.cookie.indexOf(";", c_start)
if (c_end == -1) c_end = document.cookie.length
// document.write(document.cookie.substring(c_start,c_end)+"
");
return unescape(document.cookie.substring(c_start, c_end))
}
}
return ""
}
(完)