Csharpessentials time

From senrecep/CSharpEssentials · View interactive version

Csharpessentials time is an AI agent skill from the GitHub repository senrecep/CSharpEssentials. Use when you need testable time. Inject IDateTimeProvider (DateTimeProvider over TimeProvider in production, FakeDateTimeProvider with Advance/SetTime in tests), plus DateTime/DateOnly extensions ToDateOnly/ToTimeOnly, NextDayOfWeek/PreviousDayOfWeek and GetAge.

How to use this skill

Skill file

CSharpEssentials.Time

Testable time abstraction built on .NET's TimeProvider. Inject IDateTimeProvider instead of calling DateTime.UtcNow in domain or service code.

dotnet add package CSharpEssentials.Time
using CSharpEssentials.Time;

IDateTimeProvider

public interface IDateTimeProvider
{
    TimeZoneInfo TimeZone    { get; }   // DateTimeProvider: TimeZoneInfo.Local
    TimeZoneInfo TimeZoneUtc { get; }   // TimeZoneInfo.Utc

    DateTime       UtcNowDateTime { get; }   // Kind == Utc
    DateTimeOffset UtcNow         { get; }

    // not in the netstandard2.1 build:
    DateOnly UtcNowDate { get; }
    TimeOnly UtcNowTime { get; }
}

Register in DI

DateTimeProvider wraps a TimeProvider:

builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddSingleton<IDateTimeProvider, DateTimeProvider>();

Use in services

public class OrderService(IDateTimeProvider time)
{
    public Order Create(Cart cart) => new()
    {
        UserId    = cart.UserId,
        Total     = cart.Total,
        CreatedAt = time.UtcNow,
    };
}

Test with FakeDateTimeProvider

FakeDateTimeProvider ships in this package. Its time zone is UTC, and it is thread-safe.

var start = new DateTimeOffset(2025, 1, 15, 10, 0, 0, TimeSpan.Zero);
var fake  = new FakeDateTimeProvider(start);

var svc = new OrderService(fake);   // inject as IDateTimeProvider

// Advance the clock without Thread.Sleep
fake.Advance(TimeSpan.FromHours(2));
DateTimeOffset now = fake.UtcNow;   // 2025-01-15 12:00:00 +00:00

// Jump to a specific instant
fake.SetTime(new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero));

DateOnly date = fake.UtcNowDate;
TimeOnly time = fake.UtcNowTime;

Date extensions

DateTime dt = DateTime.UtcNow;
DateOnly date = dt.ToDateOnly();
TimeOnly time = dt.ToTimeOnly();

// Next/previous weekday; the current day counts only with includeCurrent: true
DateTime nextMonday = dt.NextDayOfWeek(DayOfWeek.Monday);
DateOnly lastFriday = date.PreviousDayOfWeek(DayOfWeek.Friday, includeCurrent: true);

// Age in whole years
var birthDate = new DateOnly(1990, 5, 20);
int age      = birthDate.GetAge(new DateOnly(2025, 5, 19));   // 34
int ageToday = birthDate.GetAge(dateTimeProvider);            // "today" in the IDateTimeProvider's time zone

GetAge throws ArgumentOutOfRangeException when the birth date is after the reference date.


Guidance

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.