Formatting DateTime in ASP.NET Core 3.0 using System.Text.Json
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";
});
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...