Skip to content

Instantly share code, notes, and snippets.

@martyncoup
Created April 29, 2024 14:32
Show Gist options
  • Save martyncoup/3152dc3ea8579c2474cdd66d083a9376 to your computer and use it in GitHub Desktop.
Save martyncoup/3152dc3ea8579c2474cdd66d083a9376 to your computer and use it in GitHub Desktop.
public class CustomDateTimeConverter : DateTimeConverterBase
{
private readonly string dateFormat = null;
private readonly DateTimeConverterBase innerConverter = null;
public CustomDateTimeConverter()
: this(dateFormat: null)
{
}
public CustomDateTimeConverter(string dateFormat = null)
: this(dateFormat, innerConverter: new IsoDateTimeConverter())
{
}
public CustomDateTimeConverter(string dateFormat = null, DateTimeConverterBase innerConverter = null)
{
this.dateFormat = dateFormat;
this.innerConverter = innerConverter ?? new IsoDateTimeConverter();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Date)
{
return reader.Value;
}
var isNullableType = Helper.IsNullableType(objectType);
if (reader.TokenType == JsonToken.Null)
{
if (isNullableType)
{
return null;
}
throw new JsonSerializationException($"Cannot convert null value to {objectType}.");
}
if (reader.TokenType != JsonToken.String)
{
throw new JsonSerializationException($"Unexpected token parsing date. Expected {nameof(String)}, got {reader.TokenType}.");
}
var dateToParse = reader.Value.ToString();
if (isNullableType && string.IsNullOrWhiteSpace(dateToParse))
{
return null;
}
if (string.IsNullOrEmpty(this.dateFormat))
{
return Helper.ParseDateTime(dateToParse);
}
return Helper.ParseDateTime(dateToParse, new string[] { this.dateFormat });
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
innerConverter?.WriteJson(writer, value, serializer);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment