2

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; }
}
1
  • This might help. It's old-school ASP.NET but the principles are the same given that the ASP.NET Core serialisation process uses JSON.NET. Commented Jul 31, 2018 at 11:59

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.