如何使用PHP将当前日期保存在cookie中,并在javascript中读取它


How to save current date in a cookie with PHP and read it in javascript?

我需要使用 PHP 将当前日期保存在 cookie 中,以便可以从 javascript 读取。

我想知道如何做到这一点,因为在 PHP 中获取日期的方法和格式有很多,我不确定哪一种在 javascript 中最容易阅读,对于我的实现来说最重要的是我需要能够检查自 cookie 创建以来已经过去了多少时间(它实际上是有价值的)。

我已经有一个 readCookie() 函数来获取 cookie 的值,所以我的问题只是关于保存和检索(也许解析)cookie。

我可能会使用 RFC 2822 格式的日期,这在 PHP 中date('r')。或者使用 microtime() 返回自 1/1/1970 以来的毫秒数。

然后使用 Javascript 中的 Date 对象构造函数创建一个 Date 对象,您可以修改并计算过去了多少时间。

php:

$date = new DateTime();
setcookie("timestamp", $date->getTimestamp());

.js:

function getCookie(c_name)
{
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++)
    {
        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^'s+|'s+$/g,"");
        if (x==c_name)
        {
            return unescape(y);
        }
     }
}
var timestamp = getCookie('timestamp');
var date = new Date(timestamp * 1000);

cookie 保存在浏览器上所以使用 jquery cookie 插件可以为你工作

https://github.com/carhartl/jquery-cookie

$.cookie('the_cookie'); // => "the_value"
$.cookie('not_existing'); // => undefined