Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format NodaTime date string globally in ASP.NET Core 2.1?

Currently, I am trying to use the JsonFormatters for serializing a string in ISO 8601 spec. format in my startup config, but could not get it to work.

My Startup Config is as follows:

services.AddMvcCore(
    (options) => {
        options.SslPort = 44321;
        options.Filters.Add(new RequireHttpsAttribute());
    }
)
.AddJsonFormatters(jsonSerializerSettings => {
    jsonSerializerSettings.DateParseHandling = DateParseHandling.None;
    jsonSerializerSettings.DateFormatString = "yyyy-MM-ddTHH:mm:ss.fffZ";
})
.AddApiExplorer()
.AddJsonOptions(options => {
    options.AllowInputFormatterExceptionMessages = false;
    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();

I also tried ServiceStackText which is mentioned in the documentation, but that did not work either.

 NodaSerializerDefinitions.LocalTimeSerializer.ConfigureSerializer();
 DateTimeZoneProviders.Tzdb
     .CreateDefaultSerializersForNodaTime()
     .ConfigureSerializersForNodaTime();

I keep getting the following format,

i.e. for LocalDate serialization:

{
    "patientDob": "Thursday, June 15, 2017",
}

How can I configure the string ISO 8601 spec. formatting for NodaTime date types globally?

my model,

{
    public LocalDate patientDob { get; set; }
}

and my view model/API resource:

{
    public string patientDob { get; set; }
}
like image 853
JSON Avatar asked Dec 03 '22 11:12

JSON


1 Answers

This is the problem, in your controller:

res.NodaLocalDateString = apiResource.NodaLocalDate = nodaModel.NodaLocalDate.ToString ();

You're not converting a LocalDate into JSON at all; you're converting a string into JSON, and you're obtaining that string by calling LocalDate.ToString().

Change your API resource to have a LocalDate property instead of a string property, so that the conversion is done by Json.NET instead of by you calling ToString().

like image 116
Jon Skeet Avatar answered Jan 05 '23 12:01

Jon Skeet