.Net 6 + WebApi Basics 3 - JSON Formatter
2022-12-29 21:48:13  .Net  >> .Net6  >> WebApi

JSON Formatter for Date

Why Formatting Date

When we receive the returned data, the Json time we return is a long string, which is obviously not front-end friendly.

As following example, "date" has a lot ambiguous display making people difficult to read.

1
2
3
4
5
6
{
"date": "2022-12-29T15:52:14.9140737-05:00",
"temperatureC": -8,
"temperatureF": 18,
"summary": "Bracing"
},

So we have to format the date and time in the prefered way.

Method to Format Date

First,
We need to install a add-on package with Nuget

Browse Nuget and install
Microsoft.AspNetCore.Mvc.NewtonsoftJson

Install NewtonsoftJson

Note:

while installing NewtonsoftJson, the version is chosen based on your project’s dependencies. Here I am using version 6.0.12 for .NET 6.

Then,

Find builder.Services.AddControllers() in Program.cs, and modify with following code.

"yyyy-MM-dd HH:mm:ss" is the customized format.

1
2
3
4
5
builder.Services.AddControllers()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
});

Result:

1
2
3
4
5
6
{
"date": "2022-12-29 15:55:43",
"temperatureC": 39,
"temperatureF": 102,
"summary": "Chilly"
}

Next: .Net 6 + WebApi Basics 4

Last: .Net 6 + WebApi Basics 2


Easy!
Good Day
😎