一、时间格式转换
1.新建一个格式化类DatetimeJsonConverter,继承自JsonConverter,然后重写里面的方法
public class DatetimeJsonConverter : JsonConverter<DateTime> { public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.String) { if (DateTime.TryParse(reader.GetString(), out DateTime date)) return date; } return reader.GetDateTime(); } public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) { writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss")); } }
2.修改Startup类的ConfigureServices方法
services.AddControllers().AddJsonOptions(options => { options.JsonSerializerOptions.Converters.Add(new DatetimeJsonConverter()); });
二、日期取当前时间
public int Insert(T clz) { try { PropertyInfo dt = typeof(T).GetProperty("xx"); dt.SetValue(clz, DateTime.Now); return 1; } catch { return -1; } }
标签:core,return,DateTime,JsonSerializerOptions,options,reader,格式,net,public From: https://www.cnblogs.com/chinasoft/p/16838027.html