Skip to content
  • English Deutsch

benjamin-abt.com

Performance is a feature | Cloud - AI - Azure - .NET - Sustainability

  • Home
  • Blog
  • Portfolio
    • Overview
    • Workshops & Training
    • Publications
  • Contact
  • Home
  • Blog

Convert UnixTime to DateTimeOffset with a custom System.Text.Json Converter

Convert UnixTime to DateTimeOffset with a custom System.Text.Json Converter
October 17, 2023 3 min read BEN ABT
.NET Csharp

This article was written in 2023. Versions, tools and recommendations may have changed since then. Newer posts are collected under .NET.

Some APIs do not follow standards, ignore ISO8601 and return UnixTime. This is not nice, but can be easily fixed with a custom converter for System.Text.Json.

The converter is quite simple. It expects a number and converts it into a DateTimeOffset when reading - and vice versa when writing. For compatibility reasons, the converter should not only support the resolution of seconds, because some return Unix Time as milliseconds.

C#
 1/// <summary>
 2/// Converts Unix time to nullable DateTimeOffset.
 3/// </summary>
 4public class UnixToNullableDateTimOffsetConverter : JsonConverter<DateTimeOffset?>
 5{
 6    /// <summary>
 7    /// Minimum Unix time in seconds.
 8    /// </summary>
 9    private static readonly long s_unixMinSeconds = DateTimeOffset.MinValue.ToUnixTimeSeconds();
10
11    /// <summary>
12    /// Maximum Unix time in seconds.
13    /// </summary>
14    private static readonly long s_unixMaxSeconds = DateTimeOffset.MaxValue.ToUnixTimeSeconds();
15
16    /// <summary>
17    /// Determines if the time should be formatted as seconds. False if resolved as milliseconds.
18    /// </summary>
19    public bool FormatAsSeconds { get; init; } = true;
20
21    /// <summary>
22    /// Reads and converts the JSON to type T.
23    /// </summary>
24    public override DateTimeOffset? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
25    {
26        try
27        {
28            if (reader.TryGetInt64(out long time))
29            {
30                // If FormatAsSeconds is not specified, the correct type is derived depending on whether
31                //    the value can be represented as seconds within the .NET DateTimeOffset min/max range 0001-1-1 to 9999-12-31.
32
33                // Since this is a 64-bit value, the Unixtime in seconds may exceed
34                //    the 32-bit min/max restrictions 1/1/1970-1-1 to 1/19/2038-1-19.
35                if (FormatAsSeconds || !FormatAsSeconds && time > s_unixMinSeconds && time < s_unixMaxSeconds)
36                {
37                    return DateTimeOffset.FromUnixTimeSeconds(time);
38                }
39
40                return DateTimeOffset.FromUnixTimeMilliseconds(time);
41            }
42        }
43        catch
44        {
45            // TryGetInt64 still can throw exceptions if valid is invalid (e.g. no number)
46
47        }
48
49        return null;
50    }
51
52    /// <summary>
53    /// Writes the converted value to JSON.
54    /// </summary>
55    public override void Write(Utf8JsonWriter writer, DateTimeOffset? value, JsonSerializerOptions options)
56    {
57        if (value is DateTimeOffset date)
58        {
59            if (FormatAsSeconds)
60            {
61                writer.WriteNumberValue(date.ToUnixTimeSeconds());
62            }
63            else
64            {
65                writer.WriteNumberValue(date.ToUnixTimeMilliseconds());
66            }
67        }
68        else
69        {
70            writer.WriteNullValue();
71        }
72    }
73}

The obligatory test

C#
 1public class UnixToNullableDateTimOffsetConverterTests
 2{
 3    private readonly UnixToNullableDateTimOffsetConverter _converter = new();
 4
 5    [Fact]
 6    public void TestRead()
 7    {
 8        string json = "1619827200"; // Unix timestamp for 2021-05-01
 9        Utf8JsonReader reader = new(System.Text.Encoding.UTF8.GetBytes(json));
10        reader.Read();
11
12        DateTimeOffset? result = _converter.Read(ref reader, typeof(DateTimeOffset?), new JsonSerializerOptions());
13
14        Assert.Equal(new DateTimeOffset(2021, 5, 1, 0, 0, 0, TimeSpan.Zero), result);
15    }
16
17    [Fact]
18    public void TestWrite()
19    {
20        ArrayBufferWriter<byte> buffer = new();
21        Utf8JsonWriter writer = new(buffer);
22        DateTimeOffset date = new(2021, 5, 1, 0, 0, 0, TimeSpan.Zero);
23
24        _converter.Write(writer, date, new JsonSerializerOptions());
25        writer.Flush();
26
27        string json = System.Text.Encoding.UTF8.GetString(buffer.WrittenSpan);
28        Assert.Equal("1619827200", json);
29    }
30}

Have fun!

Related articles

Production Rate Limiting in ASP.NET Core

Nov 3, 2026 - 16 min read

Production Rate Limiting in ASP.NET Core

Most ASP.NET Core rate-limiting examples stop after registering a fixed window. That is enough to demonstrate the middleware, but it is not …

The Big Decimal Bugfix with .NET 11

Nov 2, 2026 - 11 min read

The Big Decimal Bugfix with .NET 11

For more than two decades, (decimal)1.23 returned 1.23m. It looked correct, it passed every test and it was a polite lie.

Distroless, Chiseled or Alpine: Choosing a .NET Base Image

Oct 27, 2026 - 10 min read

Distroless, Chiseled or Alpine: Choosing a .NET Base Image

Distroless, Chiseled and Alpine are often compared as three equivalent Linux distributions. They are not. Alpine is a distribution built …


BEN ABT

BEN ABT

Ben is Chief Engineering Officer and Principal Software Engineer at Medialesson.de, with a strong focus on .NET and Microsoft Azure. In his professional role, he designs and builds highly scalable platforms for hybrid and cloud-based scenarios. He also advises companies and C-levels on migrating to the sovereign cloud.

He runs myCSharp.de, the largest and most active German-speaking C# community forum, actively contributes to both his own and external open-source projects and regularly shares his knowledge through his blog, at community events, conferences and as a writer for technical magazines.

Let's Work Together

Looking for an experienced Platform Architect or Engineer for your next project? Whether it's cloud migration, platform modernization or building new solutions from scratch - I'm here to help you succeed.

New Platforms

Modernization

Training & Consulting

Contact Me
X Facebook LinkedIn WhatsApp
Back Next Blog Post

Open for work!

Contact Me
BEN ABT BEN ABT Software Engineer · Microsoft MVP Passionate about .NET, Azure, performance optimization and sustainable software engineering.

Medialesson GmbH Logo

Microsoft MVP Logo

Recent posts

View all
Production Rate Limiting in ASP.NET Core

Production Rate Limiting in ASP.NET Core

Nov 3, 2026
The Big Decimal Bugfix with .NET 11

The Big Decimal Bugfix with .NET 11

Nov 2, 2026
Distroless, Chiseled or Alpine: Choosing a .NET Base Image

Distroless, Chiseled or Alpine: Choosing a .NET Base Image

Oct 27, 2026
Stop Using nginx as Your Default Static File Server in Docker

Stop Using nginx as Your Default Static File Server in …

Oct 24, 2026
Containerizing .NET in 2026 Without a Dockerfile

Containerizing .NET in 2026 Without a Dockerfile

Oct 20, 2026

Tags

.NET (195) Csharp (99) ASP.NET Core (49) Azure (41) DevOps (17) Docker (15) Microsoft (14) EF Core (11) Microsoft MVP (11) Security (11) AI (10) GitHub (10) GitHub Copilot (10) ASP.NET (9) Synology (9) .NET 11 (8) Architecture (8) Raspberry (8) Azure Functions (7) Cloudflare (7)
benjamin-abt.com

About BEN

Benjamin Abt is a Software Engineer, Platform Architect and Microsoft MVP specializing in .NET, Azure, cloud architecture, performance optimization and sustainable software development.

Connect

  • Follow me on GitHub
  • Follow me on LinkedIn
  • Follow me on Mastodon
  • Microsoft MVP profile
  • Follow SchwabenCode on GitHub
  • Follow me on X

Quick Links

  • Portfolio
  • Blog
  • Workshops & Training
  • Publications
  • Get in Touch
  • Sitemap
Open for Work

© Copyright Benjamin Abt & SchwabenCode | 2011 - 2026

Content licensed under CC BY 4.0 unless otherwise noted.

  • Impressum
  • Privacy
  • Contact