I have a class with two DateTime properties. I need to serialize each of the properties with a different format. How can I do it? I tried:
JsonConvert.SerializeObject(obj, Formatting.None,
new IsoDateTimeConverter {DateTimeFormat = "MM.dd.yyyy"});
This solution doesn't work for me because it applies date format to all the properties. Is there any way to serialize each DateTime property with different format? Maybe there is some attribute?
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With