A straightforward way to handle this situation is to subclass the IsoDateTimeConverter
to create a custom date converter for each different date format that you need. For example:
class MonthDayYearDateConverter : IsoDateTimeConverter
{
public MonthDayYearDateConverter()
{
DateTimeFormat = "MM.dd.yyyy";
}
}
class LongDateConverter : IsoDateTimeConverter
{
public LongDateConverter()
{
DateTimeFormat = "MMMM dd, yyyy";
}
}
Then you can use the [JsonConverter]
attribute to decorate the individual DateTime
properties in any classes which need custom formatting:
class Foo
{
[JsonConverter(typeof(MonthDayYearDateConverter))]
public DateTime Date1 { get; set; }
[JsonConverter(typeof(LongDateConverter))]
public DateTime Date2 { get; set; }
// Use default formatting
public DateTime Date3 { get; set; }
}
Demo:
Foo foo = new Foo
{
Date1 = DateTime.Now,
Date2 = DateTime.Now,
Date3 = DateTime.Now
};
string json = JsonConvert.SerializeObject(foo, Formatting.Indented);
Console.WriteLine(json);
Output:
{
"Date1": "03.03.2014",
"Date2": "March 03, 2014",
"Date3": "2014-03-03T10:25:49.8885852-06:00"
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…