Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize only Date part of DateTime in web api 2

Having this object :

public class Person {
    public string FirstName { get; set; }
    [DataType(DataType.Date)]
    public DateTime Birthday { get; set; }
}

Returning this object as content in Web Api 2 generates this json for Birthday :

"2014-02-20T17:00:32.7114097+00:00"

How can I make it to be : "2014-02-20" without the time part?

like image 374
Bart Calixto Avatar asked Nov 29 '22 01:11

Bart Calixto


1 Answers

By far the simplest method is to subclass the built in IsoDateTimeConverter class and set a different DateTimeFormat.

public class IsoDateConverter : IsoDateTimeConverter
{
    public IsoDateConverter() => 
        this.DateTimeFormat = Culture.DateTimeFormat.ShortDatePattern;
}

public class Foo
{
    [JsonConverter(typeof(IsoDateConverter))]
    public DateTimeOffset Date { get; set; }
}
like image 148
Muhammad Rehan Saeed Avatar answered Dec 10 '22 20:12

Muhammad Rehan Saeed