Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core Web API - How to set default Date format as yyyy-MM-dd on Swagger

Using ASP.NET Core-6 Web API for a payment project, I have these fields:

public string ReferenceNumber { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }

By default on swagger, the date fields are displayed as:

{
  "referenceNumber": "string",
  "startDate": "2022-09-01T02:25:20.619Z",
  "endDate": "2022-09-01T02:25:20.619Z"
}

On Swagger, how do I make it display the default format for StartDate and EndDate as:

{
  "referenceNumber": "string",
  "startDate": "YYYY-MM-DD",
  "endDate": "YYYY-MM-DD"
}

Thanks

like image 854
Ayobamilaye Avatar asked Oct 19 '25 15:10

Ayobamilaye


2 Answers

If you want to give a format to DateTime, your DateTime properties have to be a string.

You can generate Swagger example requests and responses with Swashbuckle. "Swashbuckle.AspNetCore.Filters"

It will help you to create your own request and response samples, something like this.

 public class Example
    {
       public string ReferenceNumber { get; set; }
       public string StartDate { get; set; }
       public string EndDate { get; set; }
    }

your request Sample:

public class SampleRequest : IExamplesProvider <Example>
{
    public Example GetExamples()
    {
        return new Example
            {
                
                ReferenceNumber = "REF001",
                StartDate = DateTime.Now.ToString("d"),
                EndDate = DateTime.Now.ToString("d")
            };
    }
}

How you will see it on swagger:

enter image description here

like image 91
JohanEcAv Avatar answered Oct 21 '25 07:10

JohanEcAv


So you can do it using Newtonsoft and set a default format for all dates. Here's a sample code

services.AddControllers()
    .AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.DateFormatString = "YYYY-MM-DD";
    });
like image 22
Carlo Luisito Avatar answered Oct 21 '25 06:10

Carlo Luisito