Specifying a custom DateTime format when deserializing json request

beginer
beginer
102 Points
36 Posts

I'm using .net core 2.0 mvc to create api project. I'm using datetime propery as a parameter in an endpoint.
Bydefault it's accepting format as follow:

  • yyyy-MM-ddTHH:mm:ss, Or
  • yyyy-MM-dd

But when passing 12 hours datetime format i.e. yyyy-MM-ddThh:mm:ss tt , igoring all properties and getting null at active method.
Is there any way to support both format i.e

  • yyyy-MM-ddTHH:mm:ss and
  • yyyy-MM-ddThh:mm:ss tt
Views: 124
Total Answered: 2
Total Marked As Answer: 0
Posted On: 02-Nov-2019 03:03

Share:   fb twitter linkedin
Answers
Rashmi
Rashmi
Member
118 Points
29 Posts
         

You can decorate the JsonConverter attribute on an as-needed basis. Json.Net already has a built-in IsoDateTimeConverter that lets us specify the date format:

class MyDateTimeConverter : IsoDateTimeConverter
{
    public MyDateTimeConverter()
    {
        base.DateTimeFormat = "yyyy-MM-ddThh:mm:ss tt";
    }
}

And use on class property:

[JsonConverter(typeof(MyDateTimeConverter))]
public DateTime timestamp { get; set; }
Posted On: 06-Nov-2019 07:40
Smith
Smith
Participant
418 Points
119 Posts
         

We can also decorate the JsonConverter attribute with datetime format as param on an as-needed basis:

class MyDateTimeConverter : IsoDateTimeConverter
{
    public MyDateTimeConverter(string format)
    {
        DateTimeFormat = format;
    }
}

And use on class property:

[JsonConverter(typeof(MyDateTimeConverter), "yyyy-MM-ddThh:mm:ss tt")]
public DateTime timestamp { get; set; }
Posted On: 13-Nov-2019 08:01
 Log In to Chat