• Register

JS操作当天有效的cookie

有个项目的应用场景需要操作当天有效的cookie,以当天23点59分59秒为例。

<script type="text/javascript">
/*
功能:set cookies
*/
function yang_setCookie(cookieName, cookieValue){
	//当前日期
	var curDate = new Date();
	
	//当前时间戳
	var curTime = curDate.getTime();
	
	//当日凌晨的时间戳, 减去一毫秒是为了防止后续得到的时间不会达到00:00:00的状态
	var curStartHours = new Date(curDate.toLocaleDateString()).getTime() - 1;
	
	//当日已经过去的时间(毫秒)
	var passedTime = curTime - curStartHours;
	
	//当日剩余时间
	var leftTamp = 24 * 60 * 60 * 1000 - passedTime;
	var leftTime = new Date();
	leftTime.setTime(leftTamp + curTime);
	//创建cookie
	document.cookie = cookieName + "=" + escape(cookieValue) + ";expires=" + leftTime.toGMTString();
}


/*
功能:get cookies
*/
function yang_getCookie(cookieName){
    var arr = document.cookie.match(new RegExp("(^| )" + cookieName + "=([^;]*)(;|$)"));
    if (arr != null){  
        return unescape(arr[2]);
    } else {  
        return null;
    }
}

var cookieValue = yang_getCookie(cookieName);

//获取cookie 示例2
function getCookie(cookieName) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(cookieName + "=")
        if (c_start != -1) {
            c_start = c_start + cookieName.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 "" } </script>
版权声明:转载请注明来自杨俊伟博客,本文地址:http://yangjunwei.com/a/1988.html
除非注明,杨俊伟博客文章均为原创,转载请注明出处和链接!
 

发表评论 

我还是想用邮箱注册

登录

忘记密码 ?

用第三方帐号快捷登录

已有账户?前往登录吧~

注册