Skip to content

Instantly share code, notes, and snippets.

@doggy8088
Created June 10, 2022 17:03
Show Gist options
  • Save doggy8088/14af407600fdbf32c9ded58a02150949 to your computer and use it in GitHub Desktop.
Save doggy8088/14af407600fdbf32c9ded58a02150949 to your computer and use it in GitHub Desktop.
public class DateOnlyConverter : JsonConverter<DateOnly>
{
private readonly string serializationFormat;
public DateOnlyConverter() : this(null) { }
public DateOnlyConverter(string? serializationFormat)
{
this.serializationFormat = serializationFormat ?? "yyyy-MM-dd";
}
public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var value = reader.GetString();
return DateOnly.Parse(value!);
}
public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options)
=> writer.WriteStringValue(value.ToString(serializationFormat));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment