How to return dates in json in ISO format but separated with space instead of T in ASP.NET MVC4 application controller
ASP.NET standard Json() method returns dates in Microsoft format and it looks like this cannot customized.
I tried Newtonsoft Json.NET.
JsonConvert.SerializeObject(Data)
returns date in proper ISO format but with T character:
2013-11-17T18:14:32
How to return dates so that space is used instead of T like
2013-11-17 18:14:32
You can do that by creating a new IsoDateTimeConverter
instance, specifying the DateTimeFormat
you want, and then passing that converter to SerializeObject()
.
Demo:
var data = new { MyDate = new DateTime(2013, 11, 17, 18, 41, 26, 835) };
IsoDateTimeConverter dateConverter = new IsoDateTimeConverter
{
DateTimeFormat = "yyyy'-'MM'-'dd HH':'mm':'ss.FFFFFFFK"
};
string json = JsonConvert.SerializeObject(data, dateConverter);
Console.WriteLine(json);
Output:
{"MyDate":"2013-11-17 18:41:26.835"}