-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Parse unix time values from the JSON
- Loading branch information
Showing
3 changed files
with
39 additions
and
5 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,29 @@ | ||
using System; | ||
using System.Text.Json.Serialization; | ||
using System.Text.Json; | ||
|
||
namespace Certstream | ||
{ | ||
public class UnixDateTimeOffsetConverter : JsonConverter<DateTimeOffset> | ||
{ | ||
public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | ||
{ | ||
if (reader.TokenType == JsonTokenType.Number) | ||
{ | ||
if (reader.TryGetInt64(out long longTime)) | ||
return DateTimeOffset.FromUnixTimeSeconds(longTime); | ||
|
||
if (reader.TryGetDouble(out double doubleTime)) | ||
return DateTimeOffset.FromUnixTimeSeconds((long)doubleTime); | ||
} | ||
|
||
throw new JsonException("Expected a number representing Unix time."); | ||
} | ||
|
||
public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options) | ||
{ | ||
long unixTime = (long)value.ToUnixTimeSeconds(); | ||
writer.WriteNumberValue(unixTime); | ||
} | ||
} | ||
} |
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