Specifying a custom DateTime format when deserializing json request

beginer
beginer
1544 Points
52 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: 3894
Total Answered: 3
Total Marked As Answer: 1
Posted On: 02-Nov-2019 03:03

Share:   fb twitter linkedin
Answers
Rashmi
Rashmi
1068 Points
19 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
2890 Points
78 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
someok
someok
10 Points
0 Posts
         

Thanks found helpful. Use following format and worked fine for me in .netcore 3.1:

[JsonConverter(typeof(DateFormatConverter), "yyyy-MM-ddThh:mm:ssZ")]
public DateTime dateTimestamp { get; set; }
Posted On: 08-Nov-2021 05:02
 Log In to Chat