javascript - 在 PHP 中将 GMT 日期格式化为整数

标签 javascript php date time

我正在 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/

相关文章:

javascript - 将 dat.GUI 严格放置在 THREE.js 场景中,不使用 <iframe>

javascript - 如何停止在子元素上触发事件而不是添加指针事件?

javascript - 如何通过隐藏输入元素将 PHP 字符串变量传递给 Javascript 函数

php - 如何在 Visual Studio Code 中使用 HTML 标记格式化 PHP 文件?

MYSQL:如何用月、日和年设置日期(makedate?)

javascript - typescript :类型 'string' 不可分配给类型 '"数字"| "2-digit"' 在 Date::toLocaleDateString()

javascript - 如何将项目插入 Mongoose 对象内的数组?

javascript - 这有点抽象,但是你能得到一个从底 Angular 之一开始的 div 吗?

javascript - 将 POST 数据发送到 PHP 脚本 - jQuery、AJAX 和 PHP

java - 对 Java Date 对象进行排序和比较会产生意外结果