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.