41 lines
1.1 KiB
C#
41 lines
1.1 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Serialization;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace DG.Core
|
|
{
|
|
public class JsonOptionsExtensions : JsonConverter<DateTime>
|
|
{
|
|
private readonly string Format;
|
|
public JsonOptionsExtensions(string format = "yyyy-MM-dd HH:mm:ss")
|
|
{
|
|
Format = format;
|
|
}
|
|
public override void Write(Utf8JsonWriter writer, DateTime date, JsonSerializerOptions options)
|
|
{
|
|
writer.WriteStringValue(date.ToString(Format));
|
|
}
|
|
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
|
{
|
|
// 获取时间类型的字符串
|
|
var dt = reader.GetString();
|
|
if (!string.IsNullOrEmpty(dt))
|
|
{
|
|
//将日期与时间之间的"T"替换为一个空格,将结尾的"Z"去掉,否则会报错
|
|
dt = dt.Replace("T", " ").Replace("Z", "");
|
|
//取到秒,毫秒内容也要去掉,经过测试,不去掉会报错
|
|
if (dt.Length > 19)
|
|
{
|
|
dt = dt.Substring(0, 19);
|
|
}
|
|
return DateTime.ParseExact(dt, Format, null);
|
|
}
|
|
return DateTime.Now;
|
|
}
|
|
}
|
|
}
|