Tuesday, September 15, 2026

C#: Using TimeProvider and FakeTimeProvider

In this post, let's have a look at TimeProvider in C#

I have seen this abstract class around for a while (it was introduced with .NET 8), but I haven't really used it up until very recently. I just love it.

Before TimeProvider, whenever I needed to control time in tests, I had to write my own abstraction, something like IDateTimeProvider wrapping DateTime.UtcNowTimeProvider is the built-in abstraction for that. It's in the System namespace and exposes members like GetUtcNow(), GetLocalNow(), GetTimestamp() and CreateTimer().

To fake the implementation like in tests, we can install the following NuGet package.
dotnet add package Microsoft.Extensions.TimeProvider.Testing
Now let's see the code.
using Microsoft.Extensions.Time.Testing;

TimeProvider timeProvider = TimeProvider.System;
Console.WriteLine($"System date: {timeProvider.GetUtcNow():yyyy-MM-dd}");

FakeTimeProvider fakeTimeProvider = new(DateTimeOffset.Parse("2500-01-01Z")); 
Console.WriteLine($"Fake date: {fakeTimeProvider.GetUtcNow():yyyy-MM-dd}");
And the output:
System date: 2026-09-15
Fake date: 2500-01-01
TimeProvider.System is the concrete implementation that gives the actual system time. FakeTimeProvider derives from TimeProvider, so it can be passed anywhere a TimeProvider is expected, and it returns whatever time we set it to.

So in the application code, I can depend on TimeProvider and register TimeProvider.System, and in tests pass in a FakeTimeProviderFakeTimeProvider also has methods like Advance(TimeSpan) and SetUtcNow(DateTimeOffset) to move time forward, which also fires any timers and completes any Task.Delay created with that provider.

More read:

Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment