49 lines
1.4 KiB
C#
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));
|
|
}
|
|
}
|
|
}
|
|
}
|