{"slug":"time-provider-2","title":"time-provider","summary":"How code reads the current time through TimeProvider instead of DateTime.UtcNow, where the system clock is registered, and how tests fix the clock with FakeTimeProvider. Use when code needs the current date or time, sets a created or modified date, or a test depends on time.","platform":"Claude","tags":[],"authorName":"LLM Mart","authorSlug":"llm-mart","score":0,"source":"github","price":null,"verified":false,"createdAt":"2026-11-27T19:09:13.465298Z","repo":{"url":"https://github.com/LeanMeanCleanApps/CleanGraphQLApi","stars":13,"forks":7,"license":"MIT","updatedAt":"2026-11-25T23:23:22Z"},"bodyHtml":"<hr>\n<h2>name: time-provider\ndescription: How code reads the current time through TimeProvider instead of DateTime.UtcNow, where the system clock is registered, and how tests fix the clock with FakeTimeProvider. Use when code needs the current date or time, sets a created or modified date, or a test depends on time.\nmetadata:\nscope: shared</h2>\n<h1>Time provider</h1>\n<h2>The rule</h2>\n<p>Nothing reads the clock directly. Code that needs the time takes <code>TimeProvider</code> through its constructor and calls <code>GetUtcNow()</code>. Production gets <code>TimeProvider.System</code>, registered with <code>TryAddSingleton</code> in <code>AddInfrastructure</code> only. The system clock is an outside dependency, and Infrastructure owns those; Application only uses the abstract <code>TimeProvider</code>, which is part of .NET and needs no package. Every host calls <code>AddInfrastructure</code>, and <code>TryAdd</code> lets a host or test register its own clock first. Tests pass a <code>FakeTimeProvider</code> (<code>Microsoft.Extensions.TimeProvider.Testing</code>) set to a fixed moment, so every date is known in advance.</p>\n<p>Times are stored and compared in UTC. Two things read the clock today. The repository stamps <code>DateCreated</code> and <code>DateModified</code> on writes, and <code>LoggingBehaviour</code> times each request with <code>GetTimestamp()</code> and <code>GetElapsedTime()</code>.</p>\n<h2>Steps</h2>\n<ol>\n<li>Take <code>TimeProvider timeProvider</code> in the constructor, check it with <code>ArgumentNullException.ThrowIfNull</code>, and keep it in a <code>private readonly</code> field.</li>\n<li>Read the time once per operation into a local (<code>var now = this.timeProvider.GetUtcNow().UtcDateTime;</code>) and use that value everywhere in the operation, so created and modified dates match.</li>\n<li>In repository tests, use the clock from <code>MovieReviewsTestDatabase</code> (fixed at 2009-12-31 23:51:01 UTC) and assert against it.</li>\n<li>To test something that depends on time passing, call <code>Advance(TimeSpan)</code> on the fake. <code>LoggingBehaviourTests</code> advance it inside the fake <code>next</code> delegate, so the logged time is exact.</li>\n</ol>\n<h2>Example</h2>\n<pre><code>// src/Infrastructure/Databases/MovieReviews/EntityFrameworkMovieReviewsRepository.cs\npublic async Task&lt;bool&gt; UpdateReview(Guid id, int stars, CancellationToken cancellationToken)\n{\n    var now = this.timeProvider.GetUtcNow().UtcDateTime;\n\n    var updated = await this.context.Reviews\n        .Where(r =&gt; r.Id == id)\n        .ExecuteUpdateAsync(\n            setters =&gt; setters\n                .SetProperty(r =&gt; r.Stars, stars)\n                .SetProperty(r =&gt; r.DateModified, now),\n            cancellationToken);\n\n    return updated &gt; 0;\n}\n</code></pre>\n<pre><code>// tests/Infrastructure.Tests.Integration/Databases/MovieReviews/EntityFrameworkMovieReviewsRepositoryTests.cs\nupdatedReview.DateModified.ShouldBe(this.database.TimeProvider.GetUtcNow().UtcDateTime);\n</code></pre>\n<h2>Don't</h2>\n<ul>\n<li>Call <code>DateTime.Now</code>, <code>DateTime.UtcNow</code> or <code>DateTimeOffset.UtcNow</code> in <code>src</code>.</li>\n<li>Read the time more than once in one operation.</li>\n<li>Store local times.</li>\n<li>Assert a date with a tolerance (\"within a second of now\"). Fix the clock and assert the exact value.</li>\n</ul>\n<p>The one exception, in a solution with authentication, is the test that creates a token for the real JWT handler, which checks expiry against the system clock (<code>tests/Presentation.Tests.Integration/Authentication/AuthenticationTests.cs</code>).</p>\n<h2>Check</h2>\n<pre><code>grep -rn \"DateTime.UtcNow\\|DateTime.Now\\|DateTimeOffset.UtcNow\" src   # expect no output\ndotnet test tests/Infrastructure.Tests.Integration\n</code></pre>\n","files":[{"path":"SKILL.md","sizeBytes":3352,"isText":true}],"reviewScore":null,"reviewSummary":null,"trust":{"provenance":"trusted-source-unreviewed","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow.","bodySource":null},"bodyLocked":false,"purchaseUrl":null,"sourceUrl":null,"report":{"provenance":"trusted-source-unreviewed","screen":{"ran":true,"outcome":"clean","suspicious":0,"notes":0,"hiddenCharacters":false},"virusScan":{"engine":"clamav","status":"clean","scannedAt":"2026-11-27T19:10:38.639338Z","sha256":"8FD4C823753AA6D0BEE43D9AE61650BE85CC092D40981F8D6D1AF71F612C815D","sizeBytes":1605},"review":null,"source":{"repositoryUrl":"https://github.com/LeanMeanCleanApps/CleanGraphQLApi","path":".agents/skills/time-provider","license":"MIT","commit":"1168fead2e0c8143a44bdce3344e0ab5fe1db90a","subtreeSha":"A13068039AB0719065035F5B5A6ACB8915FD83825F65B4B46CAF78EFEA535A9E","lastSyncedAt":"2026-11-27T19:09:06.789278Z"},"reviewedAt":"2026-11-27T19:13:35.61986Z","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow."},"install":[{"target":"skills-cli","command":"npx skills add https://github.com/LeanMeanCleanApps/CleanGraphQLApi/tree/main/.agents/skills/time-provider"},{"target":"claude-code","command":"claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install leanmeancleanapps-cleangraphqlapi@llmmart"},{"target":"git","command":"git clone https://github.com/LeanMeanCleanApps/CleanGraphQLApi.git"}]}