Search code examples
jsonasp.net-core-webapidate-formattingiso8601asp.net-core-2.1

Removing time component from JSON DateTime response in .Net Core 2.1 Web API


I have an ASP .Net Core 2.1 Web API which returns a DateTime in one of its controller actions. The JSON looks like this:

1965-02-03T00:00:00

I think this is ISO 8601...

Since this is actually a date of birth, I would like it if it didn't contain a time component. .Net doesn't have a Date only data type (like my underlying MySQL database has) so I have to use a DateTime type. Is there any way to format the JSON data that goes out to the consuming client to YYYY-MM-DD?

The controller action is very simple:

    // GET: api/Persons
    [HttpGet]
    public IEnumerable<Person> GetPerson()
    {
        return _context.Persons;
    }

And the Person model is very simple too:

public partial class Person
{
    public int Id { get; set; }
    public string Forenames { get; set; }
    public string Surname { get; set; }
    public string Title { get; set; }
    public string IdNumber { get; set; }
    public DateTime? DateOfBirth { get; set; }
}

Solution

  • For configuring Json Serialize in Asp.Net Core, you could use AddJsonOptions with JsonSerializerSettings.

        //
        // Summary:
        //     Gets or sets how System.DateTime and System.DateTimeOffset values are formatted
        //     when writing JSON text, and the expected date format when reading JSON text.
        //     The default value is "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK".
        public string DateFormatString { get; set; }
    
            services.AddMvc()
            .AddJsonOptions(opt => {
                opt.SerializerSettings.DateFormatString = "yyyy-MM-dd";
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);