Good (Date)Times with Json.NET

Latest version of this guide: Serializing Dates in JSON

---

I’ve said it before, I’ll say it again: Dates in JSON are hard.

The problem comes from the JSON spec itself, there is no literal syntax for dates in JSON. The spec has objects, arrays, strings, integers and floats, but it defines no standard for what a date looks like.

The default format used by Json.NET for dates is the same one used by Microsoft: "\/Date(1198908717056)\/". You can read more about it here.

JsonConverters

With no standard for dates in JSON, the number of possible different formats when interoping with other systems is endless. Fortunately Json.NET has a solution to deal with reading and writing custom dates: JsonConverters. A JsonConverter is used to override how a type is serialized.

public class LogEntry
{
  public string Details { get; set; }
  public DateTime LogDate { get; set; }
}
 
[Test]
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"}
}

Simply pass the JsonConverter you wish to use to the Json.NET serializer.

JavaScriptDateTimeConverter

The JavaScriptDateTimeConverter class is one of the two DateTime JsonConverters that come with Json.NET. This converter serializes a DateTime as a JavaScript Date object.

new Date(1234656000000)

Technically this is invalid JSON according to the spec but all browsers, and some JSON frameworks including Json.NET, support it.

IsoDateTimeConverter

IsoDateTimeConverter seralizes a DateTime to an ISO 8601 formatted string.

"2009-02-15T00:00:00Z"

The IsoDateTimeConverter class has a property, DateTimeFormat, to further customize the formatted string.

 

One final thing to note is all date values returned by Json.NET are in UTC time.

JSON makes working with dates harder than it needs to be but with a little work it is a problem that is easily solved. Good times.

kick it on DotNetKicks.com