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.
public class Token(TimeProvider clock) { public bool IsExpired(DateTimeOffset expires) => clock.GetUtcNow() >= expires; }
Try it
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.
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
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.Systemas a singleton (services.AddSingleton(TimeProvider.System)) and takeTimeProviderin constructors. Tests then pass a fake. - Write a fake by subclassing. Override
GetUtcNow(andLocalTimeZone,GetTimestamp,CreateTimerif the code under test uses them). The NuGet packageMicrosoft.Extensions.TimeProvider.Testingprovides a readyFakeTimeProvider, but packages are not available in this sandbox, so the example writes its own. - Use
GetElapsedTimefor measuring,GetUtcNowfor stamping. Timestamps are monotonic and do not jump when the system clock is adjusted;GetUtcNowcan. - Library overloads.
Task.Delay(delay, provider),Task.WaitAsync(timeout, provider),new CancellationTokenSource(delay, provider)andnew PeriodicTimer(period, provider)all schedule against the given provider, so a fake can complete them without waiting. - Remember to dispose timers.
ITimerimplementsIDisposableandIAsyncDisposable. - It is not a replacement for
DateTimetypes. It returnsDateTimeOffset; convert with.UtcDateTimewhen an API needsDateTime. - Availability. Included in .NET 8 and later; for .NET Framework and older .NET use the
Microsoft.Bcl.TimeProviderpackage.