IC Improve Code Recipes

Recipe 15.2 · C#

UTC, DateTimeOffset and a Testable Clock

Problem

Code calls DateTime.Now in hundreds of places. In the archive, roughly 20,000 hand-written C# files (19,999, or 4.6%) use DateTime.Now, in 33 of the 35 engagements with C# code. Timestamps are stored in server local time, so when the database moves to a server in another region, or the clocks change in March, the data becomes ambiguous. Tests that depend on the current time either fail at midnight or are not written at all.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not to copy: local time, no offset, no way to test.
public class ResetTokenService
{
    public void Create(User user)
    {
        user.ResetToken = Guid.NewGuid().ToString();
        user.ResetExpires = DateTime.Now.AddMinutes(30);
        Save(user);                    // column type: datetime
    }

    public bool IsValid(User user)
    {
        return DateTime.Now < user.ResetExpires;
    }
}

DateTime.Now is the server's wall clock. During the autumn daylight saving change the same local hour happens twice, so a token created at 1:50 a.m. can appear valid for an extra hour. Move the app to a container running in UTC and every stored value is now off by several hours relative to the old ones. And there is no way to test the expiry without waiting thirty minutes.

The improved recipe

C#
using System;

namespace ImproveCode.Utilities;

public sealed record ResetToken(DateTimeOffset ExpiresAtUtc);

public sealed class ResetTokenPolicy(TimeProvider clock)
{
    private static readonly TimeSpan Lifetime =
        TimeSpan.FromMinutes(30);

    public ResetToken Issue() =>
        new(clock.GetUtcNow().Add(Lifetime));

    public bool IsExpired(ResetToken token) =>
        clock.GetUtcNow() >= token.ExpiresAtUtc;
}

Register the real clock once:

C#
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddScoped<ResetTokenPolicy>();

And test with a fake one. This uses the Microsoft.Extensions.TimeProvider.Testing package and works with any test framework:

C#
using System;
using Microsoft.Extensions.Time.Testing;

namespace ImproveCode.Utilities.Tests;

public static class ResetTokenPolicyTests
{
    public static void Token_expires_after_thirty_minutes()
    {
        var clock = new FakeTimeProvider(
            new DateTimeOffset(2026, 11, 1, 5, 50, 0, TimeSpan.Zero));
        var policy = new ResetTokenPolicy(clock);
        ResetToken token = policy.Issue();

        clock.Advance(TimeSpan.FromMinutes(29));
        if (policy.IsExpired(token))
        {
            throw new InvalidOperationException("Expired early.");
        }

        clock.Advance(TimeSpan.FromMinutes(1));
        if (!policy.IsExpired(token))
        {
            throw new InvalidOperationException("Did not expire.");
        }
    }
}

How it works

TimeProvider is an abstract class in the base library since .NET 8. TimeProvider.System returns the real clock; GetUtcNow() returns a DateTimeOffset with a zero offset. Because the class receives the clock through its constructor, nothing in it reads the machine time directly, and a test can set the time to any instant, including the night the clocks change.

Before .NET 8 every team wrote its own IClock or ISystemClock interface. If you have one, keep it or make it a thin adapter over TimeProvider; the important part is that business code asks for the time instead of grabbing it.

DateTimeOffset carries its offset from UTC, so a value can never be misread as local time. I use it for every instant: when something happened or when something expires. DateTime is still fine when the value really is local and unattached to a moment, such as a store's opening time, and DateOnly is right for birthdays, due dates and business days.

On the SQL Server side, store instants as datetime2(3) holding UTC, with a name that says so (CreatedUtc), or as datetimeoffset(3). Use SYSUTCDATETIME() for defaults instead of GETDATE(), which returns the server's local time.

Variations and pitfalls

  • DateTime.UtcNow is still better than DateTime.Now when you can't inject a clock, for example in a static field initializer. It's the first fix to make in old code.
  • Don't call ToLocalTime() on a web server. The server's time zone is not the user's. Convert for display with an explicit zone, as in the next recipe.
  • FakeTimeProvider also drives timers and Task.Delay(TimeSpan, TimeProvider), which makes retry and timeout code testable too.
  • When reading datetime columns with ADO.NET you get DateTimeKind.Unspecified. If the column holds UTC, call DateTime.SpecifyKind(value, DateTimeKind.Utc) at the data boundary so the kind is right everywhere else.

On .NET Framework

TimeProvider is available for .NET Framework 4.6.2 and later through the Microsoft.Bcl.TimeProvider package, so you can introduce the same abstraction in a 4.8 application before migrating it.