Skip to content

Date and time standard

This page sets the rules for code that reads the current time, waits, schedules work or converts timestamps. It is written for engineers who write or review such code and its tests.

ConnectSoft code uses System.TimeProvider, the time abstraction built into .NET. It is an abstract class, not an interface: code depends on TimeProvider, production registers TimeProvider.System, and tests pass a FakeTimeProvider from the Microsoft.Extensions.TimeProvider.Testing package. A test can then set the time and move it forward without waiting, and every component that takes the same provider sees the same time.

How dates are displayed to users is covered by the accessibility and RTL standard. How tests stay deterministic is covered by CS-TST-007, and fake clocks in Orleans hosts by CS-ORL-005.

Rules

CS-TIM-001: Read the current time only from an injected TimeProvider

Severity: major · Applies to: service, library, api-client, blazor, template · Enforced by: manual (target: ENF-066) · Status: active

Why

Code that reads DateTime.UtcNow cannot be tested at a chosen time. Its tests either cannot check time-dependent behaviour, such as an expiry or a schedule, or they compare against the real clock with a tolerance and fail at random near a boundary. DateTime.Now and DateTime.Today also depend on the server's time zone, which differs between developer machines, build agents and production.

Do

  • Take a TimeProvider in the constructor, keep it in a private readonly field, and read the time with GetUtcNow().
  • Register TimeProvider.System once, in the application model of the host: services.TryAddSingleton(TimeProvider.System);.
  • In a library used without dependency injection, accept an optional TimeProvider parameter or options property, and fall back to TimeProvider.System when none is given.
  • Read the time once per operation and pass the value on, so that every record the operation writes carries the same timestamp.

Don't

  • Call DateTime.Now, DateTime.UtcNow, DateTime.Today, DateTimeOffset.Now or DateTimeOffset.UtcNow in production code.
  • Reference TimeProvider.System outside the composition root and the library fallback.
  • Add a custom clock abstraction such as IClock, ISystemClock or IDateTimeProvider.

Example

public sealed class OrderExpiryPolicy
{
    private readonly TimeProvider timeProvider;

    public OrderExpiryPolicy(TimeProvider timeProvider)
    {
        ArgumentNullException.ThrowIfNull(timeProvider);
        this.timeProvider = timeProvider;
    }

    public bool IsExpired(Order order)
    {
        ArgumentNullException.ThrowIfNull(order);
        return order.ExpiresAt <= this.timeProvider.GetUtcNow();
    }
}

How to check

  • Search the change for DateTime.Now, DateTime.UtcNow, DateTime.Today, DateTimeOffset.Now and DateTimeOffset.UtcNow outside test code.
  • Search the change for TimeProvider.System outside the composition root and library fallbacks.
  • Search the change for a new clock abstraction, such as an IClock, ISystemClock or IDateTimeProvider type, and for injections of one.

CS-TIM-002: Wait and schedule through the TimeProvider

Severity: major · Applies to: service, library, api-client, blazor, template · Enforced by: manual (target: ENF-066) · Status: active

Why

A delay, a timeout or a timer that uses the real clock makes a test wait in real time. A retry with a 30-second back-off makes the test take 30 seconds, or the test skips the retry path entirely. The .NET APIs for delays, timeouts and timers accept a TimeProvider, so a test can move a fake clock forward and the waiting code continues at once.

Do

  • Pass the injected provider to every delay, timeout and timer:
    • Task.Delay(delay, this.timeProvider, token);
    • task.WaitAsync(timeout, this.timeProvider, token);
    • new CancellationTokenSource(timeout, this.timeProvider);
    • new PeriodicTimer(period, this.timeProvider);
    • this.timeProvider.CreateTimer(...).
  • Measure the duration of an operation for a metric with a Stopwatch (CS-SVC-002); this rule does not apply to it.
  • In Orleans grains, use the grain timer and reminder APIs; the runtime takes its time from the host's TimeProvider.

Don't

  • Call Task.Delay, WaitAsync or the CancellationTokenSource timeout constructor without a TimeProvider in production code.
  • Create a System.Threading.Timer or a System.Timers.Timer directly.

Example

using var timer = new PeriodicTimer(TimeSpan.FromMinutes(5), this.timeProvider);
while (await timer.WaitForNextTickAsync(token).ConfigureAwait(false))
{
    await this.ExpireOverdueOrders(token).ConfigureAwait(false);
}

How to check

Every Task.Delay, WaitAsync, CancellationTokenSource timeout and timer in the change passes the injected TimeProvider.

CS-TIM-003: Convert to DateTime with .UtcDateTime, never .DateTime

Severity: major · Applies to: service, library, api-client, blazor, template · Enforced by: manual (target: ENF-066) · Status: active

Why

GetUtcNow() returns a DateTimeOffset. Its .DateTime property returns the same clock reading with DateTimeKind.Unspecified, so the value no longer says that it is UTC. System.Text.Json then writes it without the Z suffix and clients read it as local time, and ToUniversalTime() treats it as server-local time and shifts it by the server's offset. .UtcDateTime returns a value with DateTimeKind.Utc.

Do

  • Keep DateTimeOffset where the field, the contract or the column allows it.
  • When a DateTime is required, convert with .UtcDateTime.
  • Store and transport timestamps in UTC.

Don't

  • Use .DateTime or .LocalDateTime on a DateTimeOffset in server code.
  • Use ToLocalTime() in server code. Conversion for display happens in the UI formatter (CS-A11Y-003).

Example

DateTimeOffset now = this.timeProvider.GetUtcNow();
order.CreatedAt = now.UtcDateTime;

How to check

  • Search the change for .GetUtcNow().DateTime, .LocalDateTime and ToLocalTime() in server code.
  • Also search server code for .DateTime on any other DateTimeOffset value.

CS-TIM-004: Test time-dependent code with FakeTimeProvider

Severity: major · Applies to: service, library, api-client, blazor, template · Enforced by: manual · Status: active

Why

FakeTimeProvider gives a test full control of the time the code under test sees. A test sets a known start time, moves the clock forward, and asserts what happened at each point, with no real waiting and no tolerance windows. It also triggers delays and timers that use the same provider, which makes retry, expiry and scheduling paths testable.

Do

  • Reference the built-in Microsoft.Extensions.TimeProvider.Testing package (namespace Microsoft.Extensions.Time.Testing) in test projects that test time-dependent code.
  • Create the fake with a fixed baseline: new FakeTimeProvider(new DateTimeOffset(2026, 1, 15, 9, 0, 0, TimeSpan.Zero)).
  • Pass the fake to the class under test, or replace the TimeProvider registration with it in a test host.
  • Move the time with Advance(...), in steps no larger than the behaviour under test needs.
  • Assert exact timestamps derived from the baseline, not values near the real clock.
  • Cover both sides of each time boundary: just before and at an expiry, a deadline or a schedule.

Don't

  • Mock TimeProvider with a mocking library, or write a custom fake clock.
  • Assert against DateTime.UtcNow with a tolerance.
  • Wait for a delay or a timer in real time.
  • Move a fake clock across months or years in a host with timers (CS-ORL-005).

Example

[TestMethod]
public void IsExpiredShouldBeTrueOnceTheExpiryTimeIsReached()
{
    // Arrange
    var clock = new FakeTimeProvider(new DateTimeOffset(2026, 1, 15, 9, 0, 0, TimeSpan.Zero));
    var policy = new OrderExpiryPolicy(clock);
    var order = new Order { ExpiresAt = clock.GetUtcNow().AddHours(1) };
    clock.Advance(TimeSpan.FromMinutes(59));
    Assert.IsFalse(policy.IsExpired(order));

    // Act
    clock.Advance(TimeSpan.FromMinutes(1));

    // Assert
    Assert.IsTrue(policy.IsExpired(order));
}

How to check

  • Tests of time-dependent code create a FakeTimeProvider with a fixed baseline and move it with Advance.
  • No new test reads the real clock or waits for a real delay.