Welcome‎ > ‎Version 2‎ > ‎Reference Info‎ > ‎

JSON Date Processing

As there is no direct support for the javascript Date object in JSON we are using the workaround defined here:

http://weblogs.asp.net/bleroy/archive/2008/01/18/dates-and-json.aspx

The following javascript will parse the json syntax correctly.

var offer = { "offerId: 10, "startDate ": new Date(1308069023484)" };
alert(offer.startDate);


However the above will not pass strict json validation.  We run some preprocessing on the json to make it pass json validation. This is a sample of what the date field will look like when it comes down through json.

JSON.html
{
    "offerId":10,
    "startDate":"\/Date(1308069023484)\/"
}


Below are some code snippets for converting our json into a proper Date object for the respective language.

JavaScript
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js"></script>
<script type="text/javascript">
    $.get("/json.html", null, function (offerString) {
        offerString = offerString.replace(/"\\\/Date\((\d+)(?:-\d+)?\)\\\/"/g, "new Date($1)")
        var offer = eval('(' + offerString + ')');
      
        alert(offer.startDate);
    });
</script>


.NET
using (var client = new WebClient())
{
    var text = client.DownloadString("http://website.com/json.html");
    var offer = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(text);
   
    Console.WriteLine(offer["startDate"]);
}

.PHP
<?php
    $ch = curl_init('/json.html');
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1) ;
    $result = curl_exec($ch);
    curl_close($ch);
    $obj = json_decode($result);

    foreach($obj as $var => $value) {
        if(gettype($value) == "string" && (preg_match_all("/^\/Date\((\(?[0-9]*)\)\/$/",$value,$matches))) {
            $obj->$var = new DateTime('@'.(int)($matches[1][0]/1000));
        }
    }
   
    print_r($obj->startDate);
?>


Comments