How do I save the current date in a cookie with PHP and read it in javascript?

advertisements

I need to save current date in a cookie using PHP so it's readable from javascript.

I'm wondering how to do it since there are a lot of ways and formats of getting the date in PHP and I'm not sure which one will be the easiest to read in javascript, the most important thing for my implementation is that I need to be able to check with plain JS how much time has passed since the cookie's creation (it's value actually).

I already have a readCookie() function that get's a cookie's value, so my question is only about saving and retrieving (and maybe parsing) the cookie.


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);