Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing multiple DateTime properties in the same class using different formats for each one

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?

like image 514
Andrei Avatar asked Jul 25 '13 11:07

Andrei


1 Answers

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"
}
like image 74
Brian Rogers Avatar answered Sep 28 '22 06:09

Brian Rogers