1

I am migrating a C# API from .NET Framework to .NET Core 3.1.

I have a requirement that some fields return yyyyMMdd only (no time) and other fields that would return the full DateTime Value (Date and Time).

In the old .NET Framework world, we could make a quick converter like this:

public class OnlyDateConverter : IsoDateTimeConverter
{
    public OnlyDateConverter()
    {
        DateTimeFormat = "yyyyMMdd";
    }
}

and use it in my model like

[JsonConverter(typeof(DateTimeConverter))]
public DateTime OrderDate { get; set; }

That isn't working in .NET Core 3.1.

When I call it via Swagger, my JSON that is returned is:

"OrderDate": "2002-05-22T00:00:00"

I know you can add a JsonSerializerOption in Startup.cs, however that will force all dates to use the same formatting. I need to pick and choose.

I have tried:

  • making multiple json converters, however they never get called/work
  • [DataType(DataType.Date)]
  • [JsonConverter(typeof(DateTimeConverter))]

I have spent all day on this. I'm hoping someone has done this and can point out my silly mistake.

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
bikeboy
  • 11
  • 1
  • 2

1 Answers1

4

This code work for me

in your output model add this :

[DataType(DataType.Date)]
[JsonConverter(typeof(JsonDateConverterExtension))]
public DateTime? DateOfBirth { get; set; }

where JsonDateConverterExtension is :

public class JsonDateConverterExtension : JsonConverter<DateTime?>
{
    public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) 

       => DateTime.ParseExact(reader.GetString(),
              "yyyy-MM-dd", CultureInfo.InvariantCulture);


    public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options)

     => writer.WriteStringValue(value?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
}
Marco
  • 86
  • 4