Skip to content

Instantly share code, notes, and snippets.

@PhonicUK
Created January 30, 2022 12:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PhonicUK/4fe80efd38a3c2d9dfdf08c2c72b941f to your computer and use it in GitHub Desktop.
Save PhonicUK/4fe80efd38a3c2d9dfdf08c2c72b941f to your computer and use it in GitHub Desktop.
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
public class DateOnlyConverter : JsonConverter<DateOnly>
{
public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TryGetDateTime(out var dt))
{
return DateOnly.FromDateTime(dt);
};
var value = reader.GetString();
if (value == null)
{
return default;
}
var match = new Regex("^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)(T|\\s|\\z)").Match(value);
return match.Success
? new DateOnly(int.Parse(match.Groups[1].Value), int.Parse(match.Groups[2].Value), int.Parse(match.Groups[3].Value))
: default;
}
public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options)
=> writer.WriteStringValue(value.ToString("yyyy-MM-dd"));
}
public class DateOnlyNullableConverter : JsonConverter<DateOnly?>
{
public override DateOnly? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TryGetDateTime(out var dt))
{
return DateOnly.FromDateTime(dt);
};
var value = reader.GetString();
if (value == null)
{
return default;
}
var match = new Regex("^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)(T|\\s|\\z)").Match(value);
return match.Success
? new DateOnly(int.Parse(match.Groups[1].Value), int.Parse(match.Groups[2].Value), int.Parse(match.Groups[3].Value))
: default;
}
public override void Write(Utf8JsonWriter writer, DateOnly? value, JsonSerializerOptions options)
=> writer.WriteStringValue(value?.ToString("yyyy-MM-dd"));
}
public static class DateOnlyConverterExtensions
{
public static void AddDateOnlyConverters(this JsonSerializerOptions options)
{
options.Converters.Add(new DateOnlyConverter());
options.Converters.Add(new DateOnlyNullableConverter());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment