I am migrating a web API from .NET Core 2.2 to 3.0 and want to use the new System.Text.Json
. When using Newtonsoft
I was able to format DateTime
using the code below. How can I accomplish the same?
.AddJsonOptions(options => { options.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc; options.SerializerSettings.DateFormatString = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZ"; });
JSON does not have a built-in type for date/time values. The general consensus is to store the date/time value as a string in ISO 8601 format.
Steps to follow the basic patternCreate a class that derives from JsonConverter<T> where T is the type to be serialized and deserialized. Override the Read method to deserialize the incoming JSON and convert it to type T . Use the Utf8JsonReader that's passed to the method to read the JSON.
The System.Text.Json namespace contains all the entry points and the main types. The System.Text.Json.Serialization namespace contains attributes and APIs for advanced scenarios and customization specific to serialization and deserialization.
Solved with a custom formatter. Thank you Panagiotis for the suggestion.
public class DateTimeConverter : JsonConverter<DateTime> { public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { Debug.Assert(typeToConvert == typeof(DateTime)); return DateTime.Parse(reader.GetString()); } public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) { writer.WriteStringValue(value.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ssZ")); } } // in the ConfigureServices() services.AddControllers() .AddJsonOptions(options => { options.JsonSerializerOptions.Converters.Add(new DateTimeConverter()); });
Migrating to Core 3 I had to replace System.Text.Json to use Newtonsoft again by :
services.AddControllers().AddNewtonsoftJson();
But I was having same issue with UTC dates in an Angular app and I had to add this to get dates in UTC:
services.AddControllers().AddNewtonsoftJson( options => options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc);
In your case you should be able to do this:
services.AddControllers().AddNewtonsoftJson(options => { options.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc; options.SerializerSettings.DateFormatString = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZ"; });
It works and I hope it helps...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With