Can a JSON object returned by PHP contain a date object

16,550

Solution 1

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.

Solution 2

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.

Solution 3

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/

Solution 4

While I agree with @postfuturist answer, there is an alternative: regular expression with syntactic sugar.

$json_data = json_encode(['test' => '__' . $_SERVER['REQUEST_TIME']]);

$json_data = preg_replace_callback('/"__([0-9]{10})"/u', function ($e) {
    return 'new Date(' . ($e[1] * 1000) . ')';
}, $json_data);

Which would produce:

string(32) "{"test":new Date(1385820141000)}"

or

Object {test: Sat Nov 30 2013 14:02:21 GMT+0000 (GMT)}

if JSON data was to be handled in JavaScript.

This would cover most of the use cases (note that UNIX timestamp is not necessarily 10 characters long). If used in production, more syntactic sugar should be used to prevent accidental replacement of the value.

This should be used only when JSON is injected at the page load time, rather than via XHR, e.g.

<html>
<head>
<script>
var myData = <?=$json_data?>;
</script>
</head>
<body>
</body>
</html>
Share:
16,550
Eric
Author by

Eric

Roboticist, engineer, and web developer Part of the NumPy development team

Updated on June 18, 2022

Comments

  • Eric
    Eric almost 2 years

    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?

  • NawaMan
    NawaMan over 14 years
    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.
  • Alex Barrett
    Alex Barrett over 14 years
    Refer to 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."
  • Eric
    Eric over 14 years
    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.
  • olliej
    olliej over 14 years
    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.
  • i.am.michiel
    i.am.michiel about 9 years
    And you would lose all timezone information. Definitely not the acceptable answer in a plural time-zone app.
  • Jack B
    Jack B over 7 years
    This wouldn't be valid JSON? It would be valid Javascript though. Correct me if i'm wrong