Skip to content

Instantly share code, notes, and snippets.

@ByteDev
Last active August 12, 2021 03:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ByteDev/d972335a24ba78c40334e446c2338228 to your computer and use it in GitHub Desktop.
Save ByteDev/d972335a24ba78c40334e446c2338228 to your computer and use it in GitHub Desktop.
using System;
using System.Text.Json;
using System.Text.Json.Serialization;

// ...

public class UnixEpochTimeToDateTimeJsonConverter : JsonConverter<DateTime>
{
    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var jsonNumber = reader.GetInt64();

        return DateTimeOffset
            .FromUnixTimeSeconds(jsonNumber)
            .UtcDateTime;
    }

    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
    {
        var unixTime = ((DateTimeOffset)value).ToUnixTimeSeconds();

        writer.WriteNumberValue(unixTime);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment