Skip to content
Advertisement

How to format a PHP date in .Net DataContractJsonSerializer format?

There is a requirement to send a date inside a JSON post using PHP in this following format

/Date(410256000000-0800)/

How do I convert a standard dd-mm-yyyy h:i:s datetime like 01-01-2013 12:00:00 to that format in PHP? Just need to know what values correspond to what in that format, not really look for a stringify things answer.

Advertisement

Answer

This should do it:

$dateTime = DateTime::createFromFormat('d-m-Y H:i:s', '01-01-2013 12:00:00');

$requiredJsonFormat = sprintf(
    '/Date(%s%s)/',
    $dateTime->format('U') * 1000,
    $dateTime->format('O')
);

echo $requiredJsonFormat; // prints '/Date(1357038000000+0100)/'

I leave it up to you to find what the formats U and O do from http://php.net/date.

An alternative would be to use PHP’s DOTNET API and use the DataContractJsonSerializer class directly from PHP. However, you’d need .NET installed on the server and using PHP’s DOTNET API is rather arcane.

The more interesting part is why you need this format at all. This is explained in a blogpost at http://weblogs.asp.net/bleroy/archive/2008/01/18/dates-and-json.aspx

But because of a strange oversight in the EcmaScript specs, there is no standard way of describing dates in JSON. […] Our current approach is using a small loophole in the JSON specs. In a JSON string literal, you may (or may not) escape some characters. Among those characters, weirdly enough, there is the slash character (‘/’). […] The new format is “/Date(1198908717056)/” where the number is again the number of milliseconds since January 1st 1970 UTC […] The point is that this disambiguates a date literal from a string that looks like the same date literal, while remaining pure JSON that will be parsed by any standard JSON parser. Of course, a parser that doesn’t know about this convention will just see a string, but parsers that do will be able to parse those as dates without a risk for false positives

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement