views:

544

answers:

4

Is there a way to create a JSON object in PHP that contains a javascript date object? Does json_encode automatically convert PHP's DateTime to Javascript's date?

+1  A: 

Short answer: no.

JSON is just text, and all values are either arrays, objects, numbers, strings, booleans or null. The "object" in this case is basically just a PHP array - it can't have methods. You need to manually convert the dates (which will be strings) into Dates.

The formal definition of JSON is at http://www.json.org/

Neall
+2  A: 

The JavaScript Date object is not valid JSON and is only seen in the wild because a lot of people parse their JSON with a full-blown eval().

An easy, human-readable alternative would be to send the date as a string in a format supported by Date.parse().

Your JSON:

{
    date: '<?php echo date("r", $myDate); ?>'
}

Your JavaScript:

var myDateObj = new Date(Date.parse(myJSON.date));

Source: http://json.org/ - See the box on the right for a list of valid JSON data types.

Alex Barrett
I was hoping I could somehow automate it through `json_encode` as I have a large associative array of which only some values (`$dates[i]["start"]`) are dates.
Eric
A: 

Sure! Use:

var JSONWithDate = {
    "Date": new Date(<?php echo date("Y, ").(date(n) - 1).date(", j") ?>)
};

EDIT: Add code example.

Here is my code and it WORKS.

<html>
<body>
<script>
var J = { "Date": new Date(<?php echo date("Y, ").(date("n") - 1).date(", j") ?>) }
document.write(J["Date"]);
</script>
</body>
</html>

EDIT 2: Make it more like JSON.

Here is my PHP code.

<html>
<body>
<script>
<?php
function GetJSONDate($FieldName = "Date") {
    return "\"$FieldName\": new Date(".date("Y, ").(date("n") - 1).date(", j").")";
}
?>

function PrintJSONFromPHP(pJSONStr) {
    var aJSONObj = eval('('+pJSONStr+')');
    document.write(aJSONObj["Date"]);
}

var aJSONStr = '{ <?php echo GetJSONDate($FieldName = "Date"); ?> }';
PrintJSONFromPHP(aJSONStr);
</script>
</body>
</html>

It generate the following HTML code:

<html>
<body>
<script>
function PrintJSONFromPHP(pJSONStr) {
    var aJSONObj = eval('('+pJSONStr+')');
    document.write(aJSONObj["Date"]);
}

var aJSONStr = '{ "Date": new Date(2009, 8, 15) }';
PrintJSONFromPHP(aJSONStr);
</script>
</body>
</html>

When run, it shows:

Tue Sep 15 2009 00:00:00 GMT-0600 (CST) 

If you can pass a string that look like JavaScript object literal (without using variable inside it), the string can be eval to be turned to an object. This means that you can use it as JSON.

Hope this helps.

NawaMan
Your example may work, but it is JavaScript and not JSON.
Alex Barrett
Sorry for my ignorant but I fail to see what "it is JavaScript and not JSON" means. JSON is a kind of JavaScript object literal which as be eval as stirng. See my edit (I see a code that make it look more like JSON) but the idea is exactly the same.
NawaMan
Refer to http://json.org/, where you can find the complete specification. A key line from the summary: "JSON is a text format that is __completely language independent__ but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, _JavaScript_, Perl, Python, and many others."
Alex Barrett
As the above people have said, JSON is not javascript -- it is a subset of the JS grammar that does not allow any non-literal expressions. Your example works because you use `eval` which is both exceedingly slow, and unsafe -- correct usage would be JSON.parse(string), which is much faster, and has the added benefit of actually being free of the many security holes present in eval.
olliej
Ok, You right. I am sorry for my mistake.
NawaMan
+4  A: 

You could pass the date / time as a UNIX timestamp which is an integer, a natively supported data type in JSON. DateTime in PHP has a "getTimestamp()" function which will give you that value.

postfuturist