-
Notifications
You must be signed in to change notification settings - Fork 22
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
+ BytecodeApi.Text.Json.Converters.DateTimeJsonConverter
- Loading branch information
Martin Fischer
committed
Oct 6, 2023
1 parent
e8219ef
commit 25d207e
Showing
1 changed file
with
35 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
using BytecodeApi.Extensions; | ||
using System.Text.Json; | ||
using System.Text.Json.Serialization; | ||
|
||
namespace BytecodeApi.Text.Json.Converters; | ||
|
||
/// <summary> | ||
/// Converts JSON values to or from <see cref="DateTime" /> values. | ||
/// </summary> | ||
public sealed class DateTimeJsonConverter : JsonConverter<DateTime> | ||
{ | ||
/// <summary> | ||
/// Reads and converts the JSON value to a <see cref="DateTime" /> value. | ||
/// </summary> | ||
/// <param name="reader">The <see cref="Utf8JsonReader" /> to read from.</param> | ||
/// <param name="typeToConvert">This parameter is ignored.</param> | ||
/// <param name="options">This parameter is ignored.</param> | ||
/// <returns> | ||
/// An equivalent <see cref="DateTime" /> value, parsed from the JSON value. | ||
/// </returns> | ||
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | ||
{ | ||
return DateTime.Parse(reader.GetString()!); | ||
} | ||
/// <summary> | ||
/// Writes the <see cref="DateTime" /> value as JSON with the format "yyyy-MM-ddTHH:mm:ss". | ||
/// </summary> | ||
/// <param name="writer">The <see cref="Utf8JsonWriter" /> to write to.</param> | ||
/// <param name="value">The <see cref="DateTime" /> value to be converted.</param> | ||
/// <param name="options">This parameter is ignored.</param> | ||
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) | ||
{ | ||
writer.WriteStringValue(value.ToStringInvariant("yyyy-MM-ddTHH:mm:ss")); | ||
} | ||
} |