.net core 3.0+ json时间格式化 ,全局配置json时间序列化格式 电脑版发表于:2023/10/20 9:53 #### 需要先创建格式类: ``` namespace WY.JBLand.API.MyResults { public class DateTimeConverters : JsonConverter<DateTime> { public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return DateTime.TryParse(reader.GetString(), out var dateTime) ? dateTime : default(DateTime); } public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) { writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss")); } } public class DateTimeNullConverters : JsonConverter<DateTime?> { public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return DateTime.TryParse(reader.GetString(), out var dateTime) ? dateTime : default(DateTime); } public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options) { writer.WriteStringValue(value == null ? "" : value.Value.ToString("yyyy-MM-dd HH:mm:ss")); } } } ``` 这里边的逻辑可以按照自己的需要修改 #### 然后在ConfigureServices中去配置使用就可以了 ``` public void ConfigureServices(IServiceCollection services) { services.AddControllers().AddJsonOptions(options => { options.JsonSerializerOptions.Converters.Add(new DateTimeConverters()); options.JsonSerializerOptions.Converters.Add(new DateTimeNullConverters()); }); services.AddApplication<WYJBLandAPIModule>(options => { //Integrate Autofac! //options.UseAutofac(); }); } ``` 需要其他什么类型的格式化都可以这样自己去写自定义的格式化类