我正在 JavaScript 中使用 this code 创建一个 cookie 。我实际上稍微改变了代码:
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 = "2017 年 10 月 6 日星期五 19:34:44 GMT 0300(东欧夏令时间);
现在我需要将此字符串转换为整数,以便与 PHP 的 time()
整数格式进行比较。
执行以下操作:
$currentTime = date('YmdHis', time());
$expire_time = date('YmdHis', strtotime($string_time));
它实际上输出:
string(14) "19700101000000" // $currentTime
string(14) "20171006162139" // $cookie_time
问题为什么$currentTime
始终是相同的19700101000000
值?
最佳答案
只需使用 unix 时间戳即可,因为您不是从 expries 设置中获取时间,而是从 cookie 值中获取时间
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 的有效时间没有任何作用。
关于javascript - 在 PHP 中将 GMT 日期格式化为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46610139/