The JSON spec allows integers, fractional numbers, strings, arrays, but when it comes to dates things are handled differently. There really is no date format in the JSON spec. Would be nice if every JSON date output would conform to ISO8601 :)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Ruby 2011-07-14 19:43:37 +0100 //ISO 8601 2011-07-14T19:43:37+0100 // Javascript Date Object new Date(1310669017000) // Javascript built-in JSON object 2012-04-23T18:25:43.511Z // .NET JavaScriptSerializer Date(1310669017000) // .NET DataContractJsonSerializer Date(1335205592410-0500) |
Some of these can easily be converted to a PHP timestamp using strtotime(), others require some more magic.
Here is a way to transform the .NET variant, something that has been haunting me in a current project ;)
1 2 3 4 |
preg_match('~(\d+)\d{3}((?:\+|-)\d+)~', $date, $match); $dt = new DateTime('@' . $match[1]); $dt = new DateTime($dt->format('Y-m-d H:i:s') . ' ' . $match[2]); $date = strtotime($dt->format('r')); |
Due to the wide usage of JSON as an exchange format, I really hope we will see a spec update in the future :)