DateTimeConverter.cs 883 B

123456789101112131415161718192021222324252627282930
  1. using System.Text.Json;
  2. using System;
  3. using System.Text.Json.Serialization;
  4. namespace ProductionLineMonitor.Web.Converter
  5. {
  6. public class DateTimeConverter : JsonConverter<DateTime>
  7. {
  8. private readonly string _dateFormatString;
  9. public DateTimeConverter()
  10. {
  11. _dateFormatString = "yyyy-MM-dd HH:mm:ss";
  12. }
  13. public DateTimeConverter(string dateFormatString)
  14. {
  15. _dateFormatString = dateFormatString;
  16. }
  17. public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  18. {
  19. return DateTime.Parse(reader.GetString());
  20. }
  21. public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
  22. {
  23. writer.WriteStringValue(value.ToString(_dateFormatString));
  24. }
  25. }
  26. }