使用 System.Text.Json 在 ASP.NET Core 3.0 中格式化 DateTime [英] Formatting DateTime in ASP.NET Core 3.0 using System.Text.Json
本文介绍了使用 System.Text.Json 在 ASP.NET Core 3.0 中格式化 DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在将 Web API 从 .NET Core 2.2 迁移到 3.0,并希望使用新的 System.Text.Json
.使用 Newtonsoft
时,我可以使用下面的代码格式化 DateTime
.我怎样才能做到这一点?
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";
});
推荐答案
通过自定义格式化程序解决.感谢 Panagiotis 的建议.
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());
});
这篇关于使用 System.Text.Json 在 ASP.NET Core 3.0 中格式化 DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文