الانتقال إلى المحتوى
.NETC#· 6 دقائق للقراءة

Why DateTime.Now Is the Wrong Timestamp: DateTime, DateTimeOffset and TimeProvider

DateTime.Now is one machine's clock reading, not a moment in time. Record instants, and get the current time from TimeProvider.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • .NET 10
محتويات المقال

A fraud rule flags a refund as "issued before the payment it refunds." The audit log agrees: payment at 10:00, refund at 08:05 the same day. In reality the refund came five minutes after the payment. The payment API runs on a VM set to UTC+2, the refund worker runs in a container on UTC, and both stamp events with DateTime.Now. Each value is a correct reading of a different clock, and the log column keeps only the reading.

The common misconception

DateTime.Now looks like the obvious answer to "when did this happen?" The name says now, every tutorial uses it, and on a developer laptop it always matches the clock on the wall. The type even has a Kind property, set to Local for Now, so the value seems to know where it came from.

It's a half-truth. On one machine, in one time zone, with no clock change in between, Now values do order events correctly. Most apps start exactly there, so the bug shows up later: a second region, a container, a cloud host on UTC, or the night the clocks change.

What actually happens

DateTime is a clock reading plus a weak hint

A DateTime is a date and a time of day, plus a Kind that says Local, Utc or Unspecified. DateTime.Now returns the local time of the current machine with Kind set to Local; DateTime.UtcNow returns UTC with Kind set to Utc.

The hint doesn't protect you. Comparison and subtraction ignore Kind and compare clock readings. Microsoft's own example subtracts DateTime.UtcNow from DateTime.Now on a Pacific-time machine, gets seven hours, and reports the local value as earlier, though both describe the same instant. Kind is also easy to lose: a value parsed from text or read from a column without an offset usually comes back as Unspecified, which the docs call ambiguous even on the machine that wrote it.

Local time is not a timeline

Local clock time can repeat and skip. In zones with , one night a year the clock goes back an hour, so the same local reading happens twice; on another night an hour of local time never exists. DateTime arithmetic doesn't check whether a local value is ambiguous or invalid, and it ignores the zone's adjustment rules. An admin changing a server's time zone has the same effect. So Now values aren't guaranteed to be in order even on a single machine.

DateTimeOffset is an instant

A DateTimeOffset stores the date and time together with its , so it identifies one point in time on any machine. Equality and comparison use that instant: 10:00 +02:00 equals 08:00 +00:00. That's why Microsoft's docs suggest it as the default date and time type for application code and list logging event and transaction times as a typical use. If you stay with DateTime, the same docs give the rule: use UTC, and set Kind to Utc, whenever you save or share a value.

TimeProvider is where "now" comes from

Since .NET 8, TimeProvider is the built-in abstraction over the clock. GetUtcNow() returns a DateTimeOffset in UTC, GetLocalNow() applies the provider's LocalTimeZone, and GetTimestamp() with GetElapsedTime() measures intervals using Stopwatch instead of the wall clock. TimeProvider.System is the real clock; tests pass a fake one. Timers accept it too: Task.Delay and CancellationTokenSource have overloads that take a TimeProvider, so timeouts become testable as well.

The fraud alert, before and after

Both tabs replay the same two events. The first stores clock readings, the second stores instants:

C# Program.cs
// Payment API on UTC+2, refund worker on UTC: both log DateTime.Nowvar paidAt = new DateTime(2026, 11, 3, 10, 0, 0);    // 08:00 UTCvar refundedAt = new DateTime(2026, 11, 3, 8, 5, 0); // 08:05 UTCif (refundedAt < paidAt){    Console.WriteLine("Refund before payment!"); // fires, wrongly}Console.WriteLine(refundedAt - paidAt); // -01:55:00

In real code neither service builds these values by hand. They ask an injected TimeProvider, which always returns an offset-aware instant:

C# RefundPolicy.cs
public sealed class RefundPolicy(TimeProvider clock){    private static readonly TimeSpan Window = TimeSpan.FromDays(14);    public bool CanRefund(DateTimeOffset paidAt) =>        clock.GetUtcNow() - paidAt <= Window;}// Program.cs: builder.Services.AddSingleton(TimeProvider.System);

In tests, FakeTimeProvider from the Microsoft.Extensions.TimeProvider.Testing package lets you set the clock with SetUtcNow or move it with Advance, so you can check day 14 and day 15 without waiting or wrapping static properties.

Myth vs reality

MythReality
DateTime.Now records when something happenedIt records one machine's local clock reading
Kind = Local keeps comparisons safeComparison and subtraction ignore Kind and compare clock readings
Now values from one server are always in orderDaylight saving changes repeat and skip local hours
DateTimeOffset knows the time zoneIt knows the offset at that instant, not the zone's future rules
Subtracting two Now values measures a durationGetTimestamp() and GetElapsedTime() measure intervals with Stopwatch

How to apply it in your project

  1. Find the clock callsSearch for DateTime.Now and DateTime.Today in code that records, compares or schedules events. Static DateTime.UtcNow calls are correct but hard to test, so move them too when you touch that code.
  2. Store instants, not readingsUse DateTimeOffset for timestamps in entities, DTOs and database columns, or a UTC DateTime with Kind set to Utc if your schema needs it. Convert to the user's time zone only when you display a value.
  3. Inject TimeProviderRegister TimeProvider.System as a singleton, take TimeProvider in constructors, and test time-dependent rules with FakeTimeProvider.
  4. Measure durations with timestampsReplace end - start on Now values with GetTimestamp() and GetElapsedTime(), so timeouts and metrics don't depend on the wall clock.

Key takeaways

  • DateTime.Now is a local clock reading from one machine, not a record of when something happened.
  • DateTime comparisons and arithmetic ignore Kind, so mixed zones and daylight saving changes give silently wrong answers.
  • DateTimeOffset, or UTC with Kind set to Utc, identifies an instant; make it your default for timestamps.
  • An offset isn't a time zone: keep a time zone ID for future local schedules.
  • Get "now" from an injected TimeProvider, and test time-dependent code with FakeTimeProvider.

📚 المصادر

  1. Compare types related to date and time — Microsoft Learn
  2. Performing arithmetic operations with dates and times — Microsoft Learn
  3. DateTime.Kind Property — Microsoft Learn
  4. What is the TimeProvider class — Microsoft Learn
  5. Banned API analyzers: how to use BannedSymbols.txt — dotnet/roslyn-analyzers

التعليقات (0)