Abstraction over DateTime/DateTimeOffset for testable time-dependent code with a fake clock for testing.
dotnet add package Philiprehberger.ClockAbstraction over DateTime/DateTimeOffset for testable time-dependent code with a fake clock for testing.
dotnet add package Philiprehberger.Clock
using Philiprehberger.Clock;
public class OrderService
{
private readonly IClock _clock;
public OrderService(IClock clock)
{
_clock = clock;
}
public Order PlaceOrder(string item)
{
return new Order(item, _clock.UtcNow);
}
}
using Philiprehberger.Clock;
// Production — uses real system time
builder.Services.AddClock();
// Testing — uses controllable fake time
builder.Services.AddFakeClock(new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero));
using Philiprehberger.Clock;
var clock = new SystemClock();
Console.WriteLine(clock.UtcNow);
Console.WriteLine(clock.Today);
using Philiprehberger.Clock;
var start = new DateTimeOffset(2026, 6, 15, 10, 0, 0, TimeSpan.Zero);
var clock = new FakeClock(start);
// Advance time manually
clock.Advance(TimeSpan.FromHours(2));
Console.WriteLine(clock.UtcNow); // 2026-06-15 12:00:00
// Set exact time
clock.SetTime(new DateTimeOffset(2026, 12, 25, 0, 0, 0, TimeSpan.Zero));
Console.WriteLine(clock.Today); // 2026-12-25
// Auto-advance on each access
clock.AutoAdvance = TimeSpan.FromMinutes(5);
Console.WriteLine(clock.UtcNow); // 2026-12-25 00:00:00
Console.WriteLine(clock.UtcNow); // 2026-12-25 00:05:00
Console.WriteLine(clock.UtcNow); // 2026-12-25 00:10:00
IClock| Member | Type | Description |
|---|---|---|
Now | DateTimeOffset | Current local date and time with offset |
UtcNow | DateTimeOffset | Current UTC date and time with offset |
Today | DateOnly | Current local date |
SystemClockReal implementation of IClock that delegates to DateTimeOffset.Now, DateTimeOffset.UtcNow, and DateTime.Today.
FakeClock| Member | Description |
|---|---|
FakeClock(DateTimeOffset initialTime) | Creates a fake clock at the given time |
Now | Returns the current fake local time |
UtcNow | Returns the current fake UTC time |
Today | Returns the current fake date |
Advance(TimeSpan duration) | Moves time forward by the specified duration |
SetTime(DateTimeOffset time) | Sets the clock to an exact time |
AutoAdvance | If set, time advances by this amount on each property access |
| Method | Description |
|---|---|
AddClock() | Registers SystemClock as IClock singleton |
AddFakeClock(DateTimeOffset? initialTime) | Registers FakeClock as IClock singleton |
dotnet build src/Philiprehberger.Clock.csproj --configuration Release
If you find this project useful: