Skip to content

Instantly share code, notes, and snippets.

@doggy8088
Created June 11, 2022 09:20
Show Gist options
  • Save doggy8088/c48beb1b45d67fe7777547794b88b6f9 to your computer and use it in GitHub Desktop.
Save doggy8088/c48beb1b45d67fe7777547794b88b6f9 to your computer and use it in GitHub Desktop.
public class TimeOnlyConverter : JsonConverter<TimeOnly>
{
private readonly string serializationFormat;
public TimeOnlyConverter() : this(null) { }
public TimeOnlyConverter(string? serializationFormat)
{
this.serializationFormat = serializationFormat ?? "HH:mm:ss.fff";
}
public override TimeOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var value = reader.GetString();
return TimeOnly.Parse(value!);
}
public override void Write(Utf8JsonWriter writer, TimeOnly 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