diff --git a/backend/api/Program.cs b/backend/api/Program.cs index d162bff93..17d7ab2ca 100644 --- a/backend/api/Program.cs +++ b/backend/api/Program.cs @@ -8,6 +8,7 @@ using Api.Services; using Api.Services.ActionServices; using Api.SignalRHubs; +using Api.Utilities; using Azure.Identity; using Microsoft.ApplicationInsights.Extensibility.Implementation; using Microsoft.AspNetCore.Authentication.JwtBearer; @@ -126,6 +127,7 @@ { options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; + options.JsonSerializerOptions.Converters.Add(new DateTimeConverter()); } ); diff --git a/backend/api/Utilities/DateTimeConverter.cs b/backend/api/Utilities/DateTimeConverter.cs new file mode 100644 index 000000000..6c715dea2 --- /dev/null +++ b/backend/api/Utilities/DateTimeConverter.cs @@ -0,0 +1,26 @@ +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Api.Utilities +{ + public class DateTimeConverter : JsonConverter + { + private const string DateFormat = "yyyy-MM-ddTHH:mm:ss.fff"; + + public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (!DateTime.TryParse(reader.GetString(), out var value)) + { + throw new JsonException($"Unexpected datetime format: '{reader.GetString()}'"); + } + return value; + } + + public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) + { + var localDateTime = value.ToLocalTime(); + writer.WriteStringValue(localDateTime.ToString(DateFormat, CultureInfo.InvariantCulture)); + } + } +}