Dates and Testing Time
Application Clock
Date uses the application's registered .NET TimeProvider, falling back to the system clock outside a service scope:
DateTimeOffset utc = Date.UtcNow;
DateTimeOffset local = Date.Now;
DateOnly today = Date.Today;Register a custom TimeProvider in a provider to change the application clock. Framework timestamps and expiration checks use this clock: models, database queues, cache, rate limiting, signed URLs, authentication, sessions, notifications, scheduling, temporary live uploads, and maintenance bypass cookies.
Expiring encrypted tokens retain ASP.NET Core's time-limited token format, so existing tokens remain readable.
Controlling Time in Tests
using var clock = Date.Freeze(DateTimeOffset.Parse("2030-01-02T03:04:05Z"));
await Cache.Put("token", "value", TimeSpan.FromMinutes(5));
clock.Advance(TimeSpan.FromMinutes(6));
Assert.False(await Cache.Has("token"));Date.Use(timeProvider) temporarily installs any TimeProvider. Both scopes restore the previous clock when disposed, support nesting, and follow the current async flow. Call them directly in the method that owns the scope, as with facade fakes.
Freezing changes the wall clock, not elapsed-time measurements or real timers such as Task.Delay and job cancellation. Redis server TTLs, filesystem timestamps, and external services keep their own clocks; use memory or database storage when testing expiration by advancing time.
Complete Example: Expiration Without Waiting
This executable self-check needs only the Blog template:
// app/Commands/ClockDemo.cs
using DotBlaze;
namespace Blog.Commands;
public class ClockDemo : Command
{
public override string Signature => "demo:clock";
public override async Task<int> Handle()
{
Cache.Fake();
using var clock = Date.Freeze(
new DateTimeOffset(2030, 1, 2, 3, 4, 5, TimeSpan.Zero));
await Cache.Put("demo:clock:token", "available", TimeSpan.FromMinutes(5));
if (!await Cache.Has("demo:clock:token"))
throw new InvalidOperationException("The value should exist before expiry.");
clock.Advance(TimeSpan.FromMinutes(6));
if (await Cache.Has("demo:clock:token"))
throw new InvalidOperationException("The value should have expired.");
Line(Date.UtcNow.ToString("O"));
return 0;
}
}Run dotblaze demo:clock. It exits successfully and prints 2030-01-02T03:10:05.0000000+00:00 without a six-minute wait. The fake uses local memory, so no live cache data is changed. Disposing the clock restores the previous clock even if an assertion throws. See ClockTokenTest.cs for framework expiration checks.