You can control the format that Json.Net uses for serializing and deserializing dates by creating a new instance of the IsoDateTimeConverter
class, setting the DateTimeFormat
property on it as you require and then passing the converter to the serializer.
Here is a demo:
class Program
{
static void Main(string[] args)
{
IsoDateTimeConverter dateConverter = new IsoDateTimeConverter
{
DateTimeFormat = "dd.MM.yyyy"
};
Foo foo = new Foo { Date = new DateTime(2014, 3, 12) };
// serialize an object containing a date using the custom date format
string json = JsonConvert.SerializeObject(foo, dateConverter);
Console.WriteLine(json);
// deserialize the JSON with the custom date format back into an object
Foo foo2 = JsonConvert.DeserializeObject<Foo>(json, dateConverter);
Console.WriteLine("Day = " + foo2.Date.Day);
Console.WriteLine("Month = " + foo2.Date.Month);
Console.WriteLine("Year = " + foo2.Date.Year);
}
}
class Foo
{
public DateTime Date { get; set; }
}
Output:
{"Date":"12.03.2014"}
Day = 12
Month = 3
Year = 2014
Note: with this approach, the date format will be applied to all dates on all objects you are serializing or deserializing. If you require different formats for different dates, then see this question which offers a couple of possible solutions.