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
?
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.
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.
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.
❮ 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With