Formatting DateTime in ASP.NET Core 3.0 using System.Text.Json

后端 未结 2 1615
时光说笑
时光说笑 2020-12-01 07:55

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 Date

相关标签:
2条回答
  • 2020-12-01 08:35

    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...

    0 讨论(0)
  • 2020-12-01 08:36

    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());
         });
    
    0 讨论(0)
提交回复
热议问题