JsonDateOnlyConverter.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. using System.Globalization;
  2. using System.Text.Json;
  3. using System.Text.Json.Serialization;
  4. namespace OnlineMetodist.API.Services
  5. {
  6. //public class JsonDateOnlyConverter : JsonConverter<DateOnly>
  7. //{
  8. // // Define the date format the data is in
  9. // private const string DateFormat = "yyyy-MM-dd";
  10. // // This is the deserializer
  11. // public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  12. // {
  13. // return DateOnly.ParseExact(reader.GetString()!,
  14. // DateFormat);
  15. // }
  16. // // This is the serializer
  17. // public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options)
  18. // {
  19. // writer.WriteStringValue(value.ToString(
  20. // DateFormat, CultureInfo.InvariantCulture));
  21. // }
  22. //}
  23. public class DateOnlyJsonConverter : JsonConverter<DateOnly>
  24. {
  25. private const string Format = "yyyy-MM-dd";
  26. public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  27. {
  28. return DateOnly.ParseExact(reader.GetString()!, Format, CultureInfo.InvariantCulture);
  29. }
  30. public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options)
  31. {
  32. writer.WriteStringValue(value.ToString(Format, CultureInfo.InvariantCulture));
  33. }
  34. }
  35. }