2017-10-06 50 views
0

我使用this code在JavaScript中创建了一个cookie。其实,我改变了代码一点:将GMT日期格式化为PHP中的整数

function setCookie (name,value,days) { 
    var expires, newValue; 
    if (days) { 
     var date = new Date(); // days = 0.0006944444; // testing with one minute 
     date.setTime(date.getTime()+(days*24*60*60*1000)); 
     expires = "; expires="+date.toString(); 
     newValue = encodeURIComponent(value)+'|'+date+expires; 
    } else expires = ""; 
    document.cookie = name+"="+(newValue)+"; path=/"; 
} 

所以上面的函数发送encodeURIComponent(value)+'|'+date+expires的价值。在PHP中我可以做explode('|',$_COOKIE['my-key'])采用这样的格式日期:

$string_time = "Fri Oct 06 2017 19:34:44 GMT 0300 (Eastern European Summer Time);

现在我需要这个字符串转换为整数来对PHP的time()整数格式进行比较。

执行以下操作:

$currentTime = date('YmdHis', time()); 
$expire_time = date('YmdHis', strtotime($string_time)); 

它实际上输出这样的:

string(14) "19700101000000" // $currentTime 
string(14) "20171006162139" // $cookie_time 

问题为什么$currentTime总是相同19700101000000价值?

+0

这很混乱?很明显,你没有从设置的cookie中获取到期时间,但是从创建UTC日期的脚本中获得某种方式。为什么不把它当作unix时间戳呢? – adeneo

+0

这是我第一次这样做,也许你可以阐明哪些值应该设置为UNIX时间戳? – thednp

+0

你从哪里得到'$ string_time',你是如何得到它到服务器的? – adeneo

回答

2

只需使用Unix时间戳,而不是,因为你不从expries设置获取时间,但是从饼干值

function setCookie (name,value,days) { 
    var expires, newValue; 

    if (days) { 
     var date = new Date(); 
     date.setTime(date.getTime()+(days*24*60*60*1000)); 
     expires = "; expires="+date.toUTCString(); 
     newValue = date.getTime()/1000; 
    } else { 
     expires = ""; 
    } 
    document.cookie = name+"="+(newValue)+"; path=/"; 
} 

现在你可以从time()直接进行比较的PHP unix时间戳和以秒为单位获得差异。

请注意,您甚至没有使用expires变量,所以这对于cookie的有效期有多长。

+0

不是所有的日子都是24小时长的,夏令时是观察到的,所以'(days * 24 * 60 * 60 * 1000)'可能不是正确的毫秒数:[*如何在今天的日期添加天数?* ](https://stackoverflow.com/questions/3818193/how-to-add-number-of-days-to-todays-date)。 – RobG

+0

@RobG - unix时间戳记是秒数,或者是以毫秒为单位的javascript,因为它不包含任何时区数据或夏令时,因此没有任何内容可以解释。 – adeneo

+0

该函数具有* days *参数,但使用毫秒设置该值。在当地时间,在一天的凌晨4点设置的cookie可能会在某一天的凌晨3点或5点过期(假设夏令时偏移为1小时),即经过24小时的倍数,但以天为单位稍微多或少。 – RobG