Files
zszq-trs/Framework/SharedWebApi/Converters/IsoDateTimeConverter_Nullable.cs
T
2024-05-09 14:06:26 +08:00

49 lines
1.4 KiB
C#

using Newtonsoft.Json;
using System;
using System.Globalization;
namespace YLErp.Converter2
{
public class IsoDateTimeConverterNullable : JsonConverter<DateTime?>
{
public IsoDateTimeConverterNullable() { }
public IsoDateTimeConverterNullable(string format)
{
DateTimeFormat = format;
}
public string DateTimeFormat { get; set; } = "yyyy/MM/dd";
public override DateTime? ReadJson(JsonReader reader, Type objectType, DateTime? existingValue, bool hasExistingValue, JsonSerializer serializer)
{
if (string.IsNullOrWhiteSpace(reader.Value?.ToString()) && (Nullable.GetUnderlyingType(objectType) != null))
{
return null;
}
DateTime date;
try
{
date = DateTime.ParseExact(reader.Value?.ToString(), DateTimeFormat, CultureInfo.InvariantCulture);
}
catch (Exception)
{
date = DateTime.Parse(reader.Value?.ToString());
}
return date;
}
public override void WriteJson(JsonWriter writer, DateTime? value, JsonSerializer serializer)
{
if (!value.HasValue)
{
writer.WriteNull();
}
else
{
writer.WriteValue(value.Value.ToString(DateTimeFormat));
}
}
}
}