-
Notifications
You must be signed in to change notification settings - Fork 37
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Change utc to local time upon json serialization
- Loading branch information
1 parent
15e6a21
commit d87a79d
Showing
2 changed files
with
28 additions
and
0 deletions.
There are no files selected for viewing
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
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
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)); | ||
} | ||
} | ||
} |