Time plays an important role in many application features. An application may need to expire a session, calculate an order deadline, schedule a reminder, validate an OTP, or determine whether a subscription is still active.

These operations often depend on the current date and time. In C#, developers commonly use DateTime.Now, DateTime.UtcNow, and DateTimeOffset.UtcNow to obtain the current time.

The problem appears when this code needs to be tested.

Imagine a service that allows a user to reset a password using a token that remains valid for 15 minutes. The application generates the token at the current time and checks its expiration when the user submits it.

A test for this behavior may need to wait for the token to expire. Another test may depend on the exact moment when the token becomes invalid. Both approaches can make the test suite slow and unreliable.

.NET provides TimeProvider to solve this problem. It allows application code to obtain time through an injectable abstraction instead of directly depending on the system clock.

With TimeProvider, developers can control time during tests, advance it without waiting in real time, and test time-dependent behavior more reliably.

In this article, we will explore TimeProvider, how to use it in C# applications, how to test expiration and scheduling logic, and how to apply it in production applications.

Why Directly Using DateTime.UtcNow Makes Testing Difficult

Consider a subscription service that determines whether a subscription is active.

C#
public sealed class SubscriptionService
{
    public bool IsActive(DateTime expirationDate)
    {
        return DateTime.UtcNow < expirationDate;
    }
}

The implementation is simple, but it depends directly on the current system time.

Suppose a test needs to verify that a subscription expires on a particular date. The test must calculate its expected result using the current clock.

C#
[Fact]
public void Subscription_ShouldBeActive()
{
    var service = new SubscriptionService();

    var expirationDate = DateTime.UtcNow.AddDays(10);

    var result = service.IsActive(expirationDate);

    Assert.True(result);
}

This test usually works, but it does not give the developer complete control over time.

Testing the exact expiration boundary becomes more difficult. Tests involving short expiration periods may also become sensitive to execution delays and timing differences.

A better design separates the application's time-dependent logic from the system clock.

What Is TimeProvider in .NET?

TimeProvider is an abstraction provided by .NET for accessing time-related functionality.

It allows an application to obtain the current time and create time-based operations without directly depending on DateTime.Now or DateTime.UtcNow.

Some important members include:

Member

Purpose

GetUtcNow()

Returns the current UTC time as DateTimeOffset

GetLocalNow()

Returns the current local time

GetTimestamp()

Returns a timestamp suitable for measuring elapsed time

GetElapsedTime()

Calculates elapsed time between timestamps

CreateTimer()

Creates a timer using the provider's time source

System

Provides the default system-based implementation

The standard System implementation uses the actual system clock.

For tests, developers can use FakeTimeProvider from the Microsoft.Extensions.TimeProvider.Testing package.

The important advantage is that application code can depend on TimeProvider while tests decide how time should behave.

Installing the Required Testing Package

The TimeProvider abstraction is available in modern .NET versions.

For testing, install the Microsoft.Extensions.TimeProvider.Testing package.

Using the .NET CLI:

Bash
dotnet add package Microsoft.Extensions.TimeProvider.Testing

This package provides FakeTimeProvider, which allows tests to control the current time.

It can also advance time and trigger supported time-based operations without waiting for the real clock.

Refactoring Application Code to Use TimeProvider

Let's update the subscription example.

Instead of calling DateTime.UtcNow directly, inject TimeProvider into the service.

C#
public sealed class SubscriptionService
{
    private readonly TimeProvider _timeProvider;

    public SubscriptionService(
        TimeProvider timeProvider)
    {
        _timeProvider = timeProvider;
    }

    public bool IsActive(DateTimeOffset expirationDate)
    {
        return _timeProvider.GetUtcNow() < expirationDate;
    }
}

The service no longer depends directly on the system clock.

The caller provides the expiration date, and the service obtains the current time through TimeProvider.

For production, register the system implementation through dependency injection.

C#
builder.Services.AddSingleton<TimeProvider>(
    TimeProvider.System);

builder.Services.AddScoped<SubscriptionService>();

The application uses the actual system time during normal execution.

During testing, the same service can receive a fake time provider.

This means the business logic does not need separate production and testing implementations.

Testing Subscription Expiration With FakeTimeProvider

Now let's write a test that controls the current time.

C#
using Microsoft.Extensions.Time.Testing;

public sealed class SubscriptionServiceTests
{
    [Fact]
    public void Subscription_ShouldBeActive_BeforeExpiration()
    {
        var fakeTimeProvider = new FakeTimeProvider(
            new DateTimeOffset(
                2026, 5, 10, 10, 0, 0,
                TimeSpan.Zero));

        var service = new SubscriptionService(
            fakeTimeProvider);

        var expirationDate = new DateTimeOffset(
            2026, 5, 20, 10, 0, 0,
            TimeSpan.Zero);

        var result = service.IsActive(expirationDate);

        Assert.True(result);
    }
}

The test starts with a fixed time.

The subscription expiration is ten days later, so the service returns true.

There is no dependency on the actual system clock. The test produces the same result regardless of when or where it runs.

The same approach can be used to test expired subscriptions.

C#
[Fact]
public void Subscription_ShouldBeInactive_AfterExpiration()
{
    var fakeTimeProvider = new FakeTimeProvider(
        new DateTimeOffset(
            2026, 5, 25, 10, 0, 0,
            TimeSpan.Zero));

    var service = new SubscriptionService(
        fakeTimeProvider);

    var expirationDate = new DateTimeOffset(
        2026, 5, 20, 10, 0, 0,
        TimeSpan.Zero);

    var result = service.IsActive(expirationDate);

    Assert.False(result);
}

The fake clock is already five days beyond the expiration date.

The test does not need to wait for five days or modify the computer's clock.

Testing the Exact Expiration Boundary

Expiration logic often contains an important boundary condition.

Should a subscription be active when the current time is exactly equal to its expiration time?

In our implementation, the comparison uses the less-than operator.

C#
return _timeProvider.GetUtcNow() < expirationDate;

This means a subscription becomes inactive when the current time reaches its expiration value.

We can test this explicitly.

C#
[Fact]
public void Subscription_ShouldBeInactive_AtExpirationTime()
{
    var expirationDate = new DateTimeOffset(
        2026, 5, 20, 10, 0, 0,
        TimeSpan.Zero);

    var fakeTimeProvider = new FakeTimeProvider(
        expirationDate);

    var service = new SubscriptionService(
        fakeTimeProvider);

    var result = service.IsActive(expirationDate);

    Assert.False(result);
}

Boundary tests are especially important for:

  • OTP expiration.

  • Password reset links.

  • Subscription renewal.

  • Payment deadlines.

  • Temporary access permissions.

  • Session expiration.

A small difference between less-than and less-than-or-equal can change the application's business behavior.

Advancing Time Without Waiting

One of the most useful features of FakeTimeProvider is the ability to advance time.

Consider a password reset token that expires after 15 minutes.

A basic implementation may look like this:

C#
public sealed class PasswordResetService
{
    private readonly TimeProvider _timeProvider;

    public PasswordResetService(
        TimeProvider timeProvider)
    {
        _timeProvider = timeProvider;
    }

    public DateTimeOffset CreateExpirationTime()
    {
        return _timeProvider.GetUtcNow()
            .AddMinutes(15);
    }

    public bool IsTokenValid(
        DateTimeOffset expirationTime)
    {
        return _timeProvider.GetUtcNow()
            < expirationTime;
    }
}

We can test the expiration behavior by advancing the fake clock.

C#
[Fact]
public void ResetToken_ShouldExpire_AfterFifteenMinutes()
{
    var fakeTimeProvider = new FakeTimeProvider(
        new DateTimeOffset(
            2026, 5, 10, 10, 0, 0,
            TimeSpan.Zero));

    var service = new PasswordResetService(
        fakeTimeProvider);

    var expirationTime = service.CreateExpirationTime();

    Assert.True(
        service.IsTokenValid(expirationTime));

    fakeTimeProvider.Advance(
        TimeSpan.FromMinutes(14));

    Assert.True(
        service.IsTokenValid(expirationTime));

    fakeTimeProvider.Advance(
        TimeSpan.FromMinutes(1));

    Assert.False(
        service.IsTokenValid(expirationTime));
}

The test advances the clock by 14 minutes and then by another minute.

The token becomes invalid exactly when it reaches its expiration time.

No real waiting is involved.

This makes it practical to test expiration behavior that would otherwise require long delays.

Using TimeProvider With Task.Delay

Time-dependent application code does not always use the current date and time directly.

Background workers often need to wait before performing another operation.

For example, a worker may check for pending notifications every 30 seconds.

A direct implementation might use Task.Delay.

C#
await Task.Delay(
    TimeSpan.FromSeconds(30),
    cancellationToken);

Although this is asynchronous, it still depends on real time.

A test that needs to verify behavior after several intervals may have to wait.

TimeProvider provides an overload of Task.Delay that accepts a time provider.

C#
await Task.Delay(
    TimeSpan.FromSeconds(30),
    timeProvider,
    cancellationToken);

Now the delay can be controlled by FakeTimeProvider.

Consider a service that waits before checking for pending work.

C#
public sealed class NotificationScheduler
{
    private readonly TimeProvider _timeProvider;

    public NotificationScheduler(
        TimeProvider timeProvider)
    {
        _timeProvider = timeProvider;
    }

    public async Task WaitForNextCheckAsync(
        CancellationToken cancellationToken)
    {
        await Task.Delay(
            TimeSpan.FromSeconds(30),
            _timeProvider,
            cancellationToken);
    }
}

A test can advance fake time to complete the delay.

C#
[Fact]
public async Task Scheduler_ShouldCompleteDelay_WhenTimeAdvances()
{
    var fakeTimeProvider = new FakeTimeProvider();

    var scheduler = new NotificationScheduler(
        fakeTimeProvider);

    using var cancellationSource =
        new CancellationTokenSource();

    var delayTask = scheduler.WaitForNextCheckAsync(
        cancellationSource.Token);

    Assert.False(delayTask.IsCompleted);

    fakeTimeProvider.Advance(
        TimeSpan.FromSeconds(30));

    await delayTask;

    Assert.True(delayTask.IsCompleted);
}

This approach is useful for testing retry delays, scheduled background work, and timeout-related behavior.

For more complex asynchronous tests, ensure that any operations scheduled by the fake clock have had an opportunity to run before asserting their results.

Using TimeProvider to Measure Elapsed Time

Another common use of time is measuring how long an operation takes.

Developers sometimes use DateTime.UtcNow for this purpose.

C#
var startTime = DateTime.UtcNow;

await ProcessOrderAsync(cancellationToken);

var elapsed = DateTime.UtcNow - startTime;

However, wall-clock time can change because of clock synchronization or system adjustments.

For measuring elapsed duration, a monotonic timestamp is more appropriate.

TimeProvider exposes GetTimestamp and GetElapsedTime for this purpose.

C#
var startTimestamp = _timeProvider.GetTimestamp();

await ProcessOrderAsync(cancellationToken);

var elapsed = _timeProvider.GetElapsedTime(
    startTimestamp);

This approach is useful for measuring:

  • API processing duration.

  • Database operation time.

  • Background job execution.

  • File processing duration.

  • Retry intervals.

  • Performance-related application metrics.

The distinction is important: use UTC date and time for business timestamps, and use monotonic timestamps for measuring elapsed time.

Common Mistakes When Using TimeProvider

Replacing Only Some Direct Clock Calls

Injecting TimeProvider into one service does not help if other parts of the same workflow continue using DateTime.UtcNow directly.

A test may control the service's clock while another component still reads the real system clock.

Review the complete time-dependent workflow and use the same abstraction consistently.

Using Local Time for Business Expiration

DateTime.Now depends on the machine's local time zone.

Applications running in different regions or containers may produce unexpected results if business expiration is calculated using local time.

Use UTC or DateTimeOffset for expiration and storage wherever possible.

Convert to local time only when presenting dates to users.

Using Wall-Clock Time for Performance Measurement

DateTime.UtcNow is useful for business timestamps, but it is not the best choice for measuring elapsed execution time.

Use GetTimestamp and GetElapsedTime instead.

Forgetting to Inject TimeProvider Into Dependencies

A service may use TimeProvider correctly while a helper class still uses direct system-clock calls.

This creates inconsistent behavior and makes tests less reliable.

Pass TimeProvider through the dependency chain wherever time-dependent behavior needs to be controlled.

Mixing Real Delays and Fake Time

If a test uses FakeTimeProvider for one operation but a normal Task.Delay for another, advancing the fake clock will not complete the real delay.

Use the TimeProvider-aware overloads for delays that must be controlled by the fake clock.

Best Practices for Time-Dependent C# Code

When designing time-dependent functionality, follow these practices:

  1. Inject TimeProvider into services that depend on the current time.

  2. Register TimeProvider.System for normal application execution.

  3. Use FakeTimeProvider in unit tests.

  4. Prefer DateTimeOffset for business timestamps and expiration values.

  5. Use UTC for storing and comparing expiration times.

  6. Use GetTimestamp and GetElapsedTime for measuring durations.

  7. Use TimeProvider-aware Task.Delay overloads for testable delays.

  8. Test exact expiration boundaries.

  9. Avoid mixing real system-clock calls with injected time.

  10. Keep time-related business rules separate from infrastructure code.

These practices make application behavior easier to test and reduce failures caused by timing differences.

Summary

Time-dependent logic can be difficult to test when application code directly depends on DateTime.Now or DateTime.UtcNow. Tests may become slow, timing-sensitive, and difficult to reproduce.

TimeProvider provides a consistent abstraction for accessing time, measuring elapsed durations, and creating time-based operations. By injecting it into application services, developers can use the real system clock in production and FakeTimeProvider in tests.

FakeTimeProvider makes it possible to advance time without waiting for real minutes, hours, or days. This is especially useful for testing OTP expiration, subscription validity, password reset tokens, scheduled tasks, and retry behavior.

The most important design decision is to treat time as a dependency rather than something that application code must access directly.

By using TimeProvider consistently, developers can write more predictable C# applications and create faster, more reliable tests for time-dependent business logic.