Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Date, Time and Globalization

The TimeProvider class

Reference for System.TimeProvider in C#: read the current time, measure elapsed time, create timers, and replace the clock with a fake in unit tests.

TimeProvider is an abstract class (added in .NET 8) that represents a source of time. The built-in TimeProvider.System reads the real clock. Code that takes a TimeProvider instead of calling DateTime.UtcNow directly can be tested with a clock you control, which makes expiry, retry and scheduling logic deterministic.

A TimeProvider offers four services: the current UTC time (GetUtcNow), the local time zone (LocalTimeZone), a high-resolution timestamp for measuring (GetTimestamp, GetElapsedTime) and timers (CreateTimer). Task.Delay, CancellationTokenSource and PeriodicTimer have overloads that accept it.

C#
public class Token(TimeProvider clock)
{
    public bool IsExpired(DateTimeOffset expires) => clock.GetUtcNow() >= expires;
}

Try it

C# A fake clock for a unit-test style check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# The system provider, timestamps and local time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public abstract class TimeProvider
{
    public static TimeProvider System { get; }
    public virtual DateTimeOffset GetUtcNow();
    public DateTimeOffset GetLocalNow();
    public virtual TimeZoneInfo LocalTimeZone { get; }
    public virtual long TimestampFrequency { get; }
    public virtual long GetTimestamp();
    public TimeSpan GetElapsedTime(long startingTimestamp);
    public TimeSpan GetElapsedTime(long startingTimestamp, long endingTimestamp);
    public virtual ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period);
}
Member Description
System The provider backed by the real clock and time zone.
GetUtcNow() The current UTC time; the member to override in a fake.
GetLocalNow() GetUtcNow() converted with LocalTimeZone.
GetTimestamp(), GetElapsedTime(...), TimestampFrequency Monotonic high-resolution measurement; ticks per second is TimestampFrequency.
CreateTimer(...) A timer returned as ITimer (disposable, supports Change).

Errors: CreateTimer throws ArgumentNullException for a null callback and ArgumentOutOfRangeException for invalid intervals.

Usage notes

  • Inject it. Register TimeProvider.System as a singleton (services.AddSingleton(TimeProvider.System)) and take TimeProvider in constructors. Tests then pass a fake.
  • Write a fake by subclassing. Override GetUtcNow (and LocalTimeZone, GetTimestamp, CreateTimer if the code under test uses them). The NuGet package Microsoft.Extensions.TimeProvider.Testing provides a ready FakeTimeProvider, but packages are not available in this sandbox, so the example writes its own.
  • Use GetElapsedTime for measuring, GetUtcNow for stamping. Timestamps are monotonic and do not jump when the system clock is adjusted; GetUtcNow can.
  • Library overloads. Task.Delay(delay, provider), Task.WaitAsync(timeout, provider), new CancellationTokenSource(delay, provider) and new PeriodicTimer(period, provider) all schedule against the given provider, so a fake can complete them without waiting.
  • Remember to dispose timers. ITimer implements IDisposable and IAsyncDisposable.
  • It is not a replacement for DateTime types. It returns DateTimeOffset; convert with .UtcDateTime when an API needs DateTime.
  • Availability. Included in .NET 8 and later; for .NET Framework and older .NET use the Microsoft.Bcl.TimeProvider package.