Created
January 30, 2022 12:45
-
-
Save PhonicUK/4fe80efd38a3c2d9dfdf08c2c72b941f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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