Time Abstraction in .NET 8

.NET 8 introduces the TimeProvider class and ITimer interface to add time abstraction functionality. This allows developers to mock time in test scenarios. Additionally, you can use the time abstraction to mock Task operations that rely on time progression using Task.Delay and Task.WaitAsync.

Code Examples:


// Get system time.
DateTimeOffset utcNow = TimeProvider.System.GetUtcNow();
DateTimeOffset localNow = TimeProvider.System.GetLocalNow();

// Create a time provider that works with a different time zone
// than the local time zone.
private class ZonedTimeProvider : TimeProvider
{
    private TimeZoneInfo _zoneInfo;
    public ZonedTimeProvider(TimeZoneInfo zoneInfo) : base()
    {
        _zoneInfo = zoneInfo ?? TimeZoneInfo.Local;
    }
    public override TimeZoneInfo LocalTimeZone => _zoneInfo;
    public static TimeProvider FromLocalTimeZone(TimeZoneInfo zoneInfo) => new ZonedTimeProvider(zoneInfo);
}

Imagine building a feature that sends reminders to users based on their local time. With the new time abstraction, you can mock different time zones and test how your reminders work around the globe without waiting for actual time to pass.


Summary: