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
TimeProviderin the constructor, keep it in aprivate readonlyfield, and read the time withGetUtcNow(). - Register
TimeProvider.Systemonce, in the application model of the host:services.TryAddSingleton(TimeProvider.System);. - In a library used without dependency injection, accept an optional
TimeProviderparameter or options property, and fall back toTimeProvider.Systemwhen 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.NoworDateTimeOffset.UtcNowin production code. - Reference
TimeProvider.Systemoutside the composition root and the library fallback. - Add a custom clock abstraction such as
IClock,ISystemClockorIDateTimeProvider.
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.NowandDateTimeOffset.UtcNowoutside test code. - Search the change for
TimeProvider.Systemoutside the composition root and library fallbacks. - Search the change for a new clock abstraction, such as an
IClock,ISystemClockorIDateTimeProvidertype, 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,WaitAsyncor theCancellationTokenSourcetimeout constructor without aTimeProviderin production code. - Create a
System.Threading.Timeror aSystem.Timers.Timerdirectly.
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
DateTimeOffsetwhere the field, the contract or the column allows it. - When a
DateTimeis required, convert with.UtcDateTime. - Store and transport timestamps in UTC.
Don't¶
- Use
.DateTimeor.LocalDateTimeon aDateTimeOffsetin server code. - Use
ToLocalTime()in server code. Conversion for display happens in the UI formatter (CS-A11Y-003).
Example¶
How to check¶
- Search the change for
.GetUtcNow().DateTime,.LocalDateTimeandToLocalTime()in server code. - Also search server code for
.DateTimeon any otherDateTimeOffsetvalue.
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.Testingpackage (namespaceMicrosoft.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
TimeProviderregistration 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
TimeProviderwith a mocking library, or write a custom fake clock. - Assert against
DateTime.UtcNowwith 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
FakeTimeProviderwith a fixed baseline and move it withAdvance. - No new test reads the real clock or waits for a real delay.