Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
.NET Core

.NET 9 TimeProvider: Testable Time Management Made Easy

- 19.08.26 - ErcanOPAK

Testing code that depends on DateTime.Now or DateTime.UtcNow is a nightmare. .NET 9’s TimeProvider solves this elegantly.

The Problem – Untestable Time:

// Hard to test
public class OrderService
{
    public bool IsOrderExpired(Order order)
    {
        // ❌ Always uses current time
        return order.CreatedDate.AddDays(1) < DateTime.UtcNow;
    }
}

// Test failure: 
// - Test at 23:59: Runs correctly
// - Test at 00:01: Fails!
// - Test on different timezone: Different results!

The Solution – TimeProvider:

// .NET 9: TimeProvider
public class OrderService
{
    private readonly TimeProvider _timeProvider;
    
    public OrderService(TimeProvider timeProvider)
    {
        _timeProvider = timeProvider;
    }
    
    public bool IsOrderExpired(Order order)
    {
        // ✅ Uses injected time provider
        return order.CreatedDate.AddDays(1) < _timeProvider.GetUtcNow();
    }
}

// Test:
var fakeTime = new FakeTimeProvider(new DateTime(2024, 1, 1, 12, 0, 0, DateTimeKind.Utc));
var service = new OrderService(fakeTime);

// Order created at 2024-01-01 00:00:00
// Should expire after 24 hours
var order = new Order { CreatedDate = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc) };

// Test at exactly 24 hours
fakeTime.Advance(TimeSpan.FromHours(24));
Assert.True(service.IsOrderExpired(order));  // ✅ Passes!

// Test at 23 hours 59 minutes
fakeTime.Reset();  // Reset to original time
fakeTime.Advance(TimeSpan.FromHours(23).Add(TimeSpan.FromMinutes(59)));
Assert.False(service.IsOrderExpired(order));  // ✅ Passes!

FakeTimeProvider Implementation:

public class FakeTimeProvider : TimeProvider
{
    private DateTimeOffset _currentTime;
    
    public FakeTimeProvider(DateTimeOffset startTime)
    {
        _currentTime = startTime;
    }
    
    public override DateTimeOffset GetUtcNow() => _currentTime;
    
    public void Advance(TimeSpan delta)
    {
        _currentTime = _currentTime.Add(delta);
    }
    
    public void SetTime(DateTimeOffset newTime)
    {
        _currentTime = newTime;
    }
    
    public void Reset()
    {
        // Reset to initial time
    }
}

Real-World Usage – Cache Expiry:

public class CacheService<T>
{
    private readonly Dictionary<string, (T Value, DateTimeOffset Expiry)> _cache = new();
    private readonly TimeProvider _timeProvider;
    private readonly TimeSpan _defaultTtl;
    
    public CacheService(TimeProvider timeProvider, TimeSpan defaultTtl)
    {
        _timeProvider = timeProvider;
        _defaultTtl = defaultTtl;
    }
    
    public void Set(string key, T value, TimeSpan? ttl = null)
    {
        ttl ??= _defaultTtl;
        var expiry = _timeProvider.GetUtcNow().Add(ttl.Value);
        _cache[key] = (value, expiry);
    }
    
    public bool TryGet(string key, out T value)
    {
        if (_cache.TryGetValue(key, out var entry))
        {
            if (entry.Expiry > _timeProvider.GetUtcNow())
            {
                value = entry.Value;
                return true;
            }
            
            _cache.Remove(key);  // Expired
        }
        
        value = default;
        return false;
    }
}

// Test:
[Fact]
public void Cache_Expires_After_TTL()
{
    var time = new FakeTimeProvider(DateTimeOffset.UtcNow);
    var cache = new CacheService<string>(time, TimeSpan.FromMinutes(5));
    
    cache.Set("key", "value");
    Assert.True(cache.TryGet("key", out _));  // ✅ Exists
    
    time.Advance(TimeSpan.FromMinutes(6));  // Advance 6 minutes
    Assert.False(cache.TryGet("key", out _));  // ✅ Expired
}

TimeProvider vs ITimer:

// Old way: System.Timers.Timer - Hard to test
public class HeartbeatService
{
    private readonly Timer _timer;
    
    public HeartbeatService()
    {
        _timer = new Timer(1000);
        _timer.Elapsed += (s, e) => SendHeartbeat();
        _timer.Start();
    }
}

// New way: TimeProvider.CreateTimer() - Testable!
public class HeartbeatService
{
    private readonly TimeProvider _timeProvider;
    private readonly ITimer _timer;
    
    public HeartbeatService(TimeProvider timeProvider)
    {
        _timeProvider = timeProvider;
        _timer = _timeProvider.CreateTimer(
            callback: _ => SendHeartbeat(),
            state: null,
            dueTime: TimeSpan.Zero,
            period: TimeSpan.FromSeconds(1)
        );
    }
    
    public void Stop() => _timer.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
}

// Test:
[Fact]
public void Heartbeat_Sends_Every_Second()
{
    var time = new FakeTimeProvider(DateTimeOffset.UtcNow);
    var service = new HeartbeatService(time);
    
    // Simulate 10 seconds passing
    for (int i = 0; i < 10; i++)
    {
        time.Advance(TimeSpan.FromSeconds(1));
        // Assert heartbeat was sent
    }
}

TimeProvider with Dependency Injection:

// Program.cs
builder.Services.AddSingleton(TimeProvider.System);  // Real time provider

// In production: Uses real time
// In tests: Injects FakeTimeProvider

TimeZone Support:

// Local time with timezone
var timeProvider = TimeProvider.System;
var localTime = timeProvider.GetLocalNow();

// Custom timezone provider
public class CustomTimeZoneProvider : TimeProvider
{
    private readonly TimeZoneInfo _timeZone;
    
    public CustomTimeZoneProvider(TimeZoneInfo timeZone)
    {
        _timeZone = timeZone;
    }
    
    public override TimeZoneInfo LocalTimeZone => _timeZone;
}

Best Practices:

✅ Inject TimeProvider into all services
✅ Use GetUtcNow() for UTC time operations
✅ Use GetLocalNow() for user-facing times
✅ Use CreateTimer() instead of System.Timers.Timer
✅ Use FakeTimeProvider for unit tests
✅ Use TimeProvider.System in DI for production
❌ Don't use DateTime.Now/UtcNow directly
❌ Don't use DateTimeOffset.Now/UtcNow directly
❌ Don't use System.Timers.Timer in new code

Related posts:

API Response Compression in .NET: 90% Smaller Payloads

API Response Compression in .NET: 90% Smaller Payloads

Rate Limiting in .NET 8: Shield Your API from DDoS Attacks Like a Pro

Rate Limiting in .NET 8: Shield Your API from DDoS Attacks Like a Pro

.NET 8 Native AOT: Build Zero-Runtime-Dependency Applications

.NET 8 Native AOT: Build Zero-Runtime-Dependency Applications

Views: 12

Post navigation

C# Span and Memory: Zero-Copy Data Processing for Maximum Performance
Docker Multi-Stage Build: Reduce .NET Image Size by 90%

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (661)
  • Add Constraint to SQL Table to ensure email contains @ (619)
  • Average of all values in a column that are not zero in SQL (577)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (553)
  • Find numbers with more than two decimal places in SQL (481)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store
  • WordPress: Fix a Navigation Block Losing Submenu Items After Sync
  • Visual Studio: Fix CodeLens Reference Counts Stuck at Stale Numbers
  • C#: Fix a UTF-8 String Literal Behaving Differently in a Switch
  • Photoshop: Fix a Liquify Mesh Snapping Back on a Smart Object
  • The AI Prompt That Turns a Crash Dump Into a Short Repro Script

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com