Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a JSON object returned by PHP contain a date object

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?

like image 544
Eric Avatar asked Sep 15 '09 17:09

Eric


People also ask

Can JSON have dates?

JSON does not have a built-in type for date/time values. The general consensus is to store the date/time value as a string in ISO 8601 format.

Can PHP return JSON?

You can simply use the json_encode() function to return JSON response from a PHP script. Also, if you're passing JSON data to a JavaScript program, make sure set the Content-Type header.

How does JSON handle data in PHP?

To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.

What is JSON response in PHP?

❮ Previous Next ❯ A common use of JSON is to read data from a web server, and display the data in a web page. This chapter will teach you how to exchange JSON data between the client and a PHP server.


1 Answers

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.

like image 125
Alex Barrett Avatar answered Sep 24 '22 16:09

Alex Barrett