tags2k tags2k - 4 months ago 15x
JSON Question

Parsing JSON DateTime from Newtonsoft's JSON Serializer

I've serialized an object using Newtonsoft's JSON serializer, and the DateTime has come through as:


When I $.evalJSON() on that, it is an object but I can't find any normal Date methods like toUTCString on it.

Any ideas what I can do with this?


Use one of the JsonConverters that come with Json.NET for working with dates to get a better format. JavaScriptDateTimeConverter will automatically give you a JavaScript date.

public class LogEntry    
  public string Details { get; set; }    
  public DateTime LogDate { get; set; }

public void WriteJsonDates()
  LogEntry entry = new LogEntry    
    LogDate = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc),    
    Details = "Application started."    

  string defaultJson = JsonConvert.SerializeObject(entry);    
  // {"Details":"Application started.","LogDate":"\/Date(1234656000000)\/"}     

  string javascriptJson = JsonConvert.SerializeObject(entry, new JavaScriptDateTimeConverter());    
  // {"Details":"Application started.","LogDate":new Date(1234656000000)}

  string isoJson = JsonConvert.SerializeObject(entry, new IsoDateTimeConverter());    
  // {"Details":"Application started.","LogDate":"2009-02-15T00:00:00Z"}    

Documentation: Serializing Dates in JSON with Json.NET