Skip to content

Commit

Permalink
Change utc to local time upon json serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
UsamaEquinorAFK committed Jan 12, 2024
1 parent 15e6a21 commit d87a79d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
2 changes: 2 additions & 0 deletions backend/api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -126,6 +127,7 @@
{
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
}
);

Expand Down
26 changes: 26 additions & 0 deletions backend/api/Utilities/DateTimeConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Api.Utilities
{
public class DateTimeConverter : JsonConverter<DateTime>
{
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));
}
}
}

0 comments on commit d87a79d

Please sign in to comment.