使用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屋!
查看全文