Skip to content

Dates, times, and time zones

Targets net11.0 csharp-15Last reviewed 2026-11-14 freshSources andrew-lock dotnet-blog jon-skeet meziantou ms-learn shay-rojansky

Four rules cover most cases:

  • Use DateTimeOffset by default, not DateTime.
  • Store timestamps in UTC, except future local events.
  • Inject TimeProvider into services. Never call DateTime.UtcNow.
  • Identify a time zone by its IANA ID (Europe/Amsterdam), never by an abbreviation or an offset.

Choosing the type

Default to DateTimeOffset. Use a narrower type only when the data has no time, no date, or no clock. Microsoft's guidance: "consider DateTimeOffset as the default date and time type for application development". (Microsoft Learn: Compare types related to date and time)

Need Type Why
An unambiguous point in time DateTimeOffset Records the UTC offset, so it identifies one instant on any machine
A whole date, no time (birthday, invoice) DateOnly A time zone can't shift it by a day; serializes less data; maps to SQL date
A time of day (opening hours, alarm) TimeOnly Wraps at 24 hours instead of overflowing like TimeSpan or DateTime
A duration or elapsed time TimeSpan An interval, not a clock reading
Zone rules and conversions TimeZoneInfo The only type that knows DST transitions
An abstract date and time, or UTC-only code DateTime Rarely needed: it can't identify an instant unless Kind is Utc

The documentation adds two caveats:

Don't assume:

  • That offsets are whole hours. Newfoundland Daylight Time is UTC−2:30.
  • That DST shifts by an hour. Lord Howe Island shifts by 30 minutes.
  • That one country agrees on DST. Its zones can differ.
  • That an abbreviation names one zone. "BST" matches three.

Anything less than an IANA ID loses information.

(Meziantou: 43 Misconceptions about date and time)

Persistence: split by kind of data, not by layer

Store machine-generated timestamps as UTC instants. Store a future or recurring event that a person enters as its local time and IANA zone ID, and derive UTC from them. The event isn't an instant until zone rules are applied, and those rules can change before it happens. (Skeet: Storing UTC is not a silver bullet)

Converting to UTC on input fails here. A conference set for 9 AM Amsterdam time on 2022-07-10 converts to 07:00Z under that day's tzdb rules. If the Netherlands drops summer time, the correct instant becomes 08:00Z. A row that stores only UTC is now an hour wrong, and the organiser's intent is gone. Store what the user entered, and cache the conversion:

LocalStart:    2022-07-10T09:00:00     ← what the user said; never mutated
TimeZoneId:    Europe/Amsterdam        ← IANA id, not an offset
UtcStart:      2022-07-10T07:00:00Z    ← derived; recomputed when tzdb updates
TimeZoneRules: 2019a                   ← optional, for resumable re-derivation

The same applies to any future meeting: "If you want to schedule a meeting at 10 AM in New York next year, do not convert to UTC and store it." (Meziantou: 43 Misconceptions about date and time)

  • Re-derive the UTC column whenever the host's tzdb changes, such as on a base image update. IANA publishes several tzdb releases a year, sometimes days before they take effect.
  • Store IANA IDs, not Windows IDs. .NET converts between them, but Windows IDs tie your data to one platform.

Provider behaviour:

When the BCL types aren't enough

Use NodaTime when the domain schedules future or recurring local-time events across zones. Otherwise, use the BCL types. NodaTime turns the schema above into types the compiler checks:

  • Instant for machine timestamps.
  • LocalDateTime and DateTimeZone for what a person enters.
  • ZonedDateTime for the derived conversion.

The cost is an adapter at every boundary the BCL types cross natively: NodaTime.Serialization.SystemTextJson, a provider plugin such as Npgsql.NodaTime, and model binding. An ordinary service gets everything it needs from DateTimeOffset, DateOnly, TimeOnly, and TimeProvider. Conflict of interest: the cited source created NodaTime. (Skeet: More fun with DateTime)

Services: inject TimeProvider, stop writing your own clock

Take TimeProvider as a dependency, and register TimeProvider.System once. Never call DateTime.UtcNow or DateTimeOffset.Now in a service, and never write an IClock abstraction. TimeProvider has been in the BCL since .NET 8, and Microsoft.Bcl.TimeProvider brings it to netstandard2.0. It provides:

  • GetUtcNow() and GetLocalNow(), which return DateTimeOffset.
  • GetTimestamp() and GetElapsedTime() for measurement.
  • CreateTimer(...).
  • LocalTimeZone, so one process can serve users in different zones.

(Microsoft Learn: What is TimeProvider?)

// Register once; TimeProvider.System is the production implementation.
builder.Services.AddSingleton(TimeProvider.System);

public sealed class OrderService(TimeProvider time)
{
    public Order Place(Basket basket) => new(basket, PlacedAt: time.GetUtcNow());
}

Pass the provider on. Task.Delay, Task.WaitAsync, and CancellationTokenSource have TimeProvider overloads. A PeriodicTimer or BackgroundService that skips them waits on the real clock, so a test can't move its time.

Two template files enforce this together. templates/Directory.Build.props adds Meziantou.Analyzer and sets TreatWarningsAsErrors, but the rules below default to info severity or off, so they never fail the build alone. dotnet_analyzer_diagnostic.severity = warning in templates/.editorconfig raises them to warnings, which TreatWarningsAsErrors makes errors. Without both files, a hand-written IClock builds cleanly. (Meziantou: Meziantou.Analyzer rules)

Rule Title Default
MA0188 Use System.TimeProvider instead of a custom time abstraction Enabled, info severity
MA0166 Forward the TimeProvider to methods that take one Enabled, info severity
MA0167 Use an overload with a TimeProvider argument Disabled; templates/.editorconfig enables it

Testing time

Use FakeTimeProvider from Microsoft.Extensions.TimeProvider.Testing. Set a start instant, and move time with Advance(TimeSpan). Its timers fire as time moves, so you can test retry, backoff, and scheduling without Thread.Sleep. A single large Advance fires every due callback at once, at the end. If a test checks how callbacks interleave, advance in small steps. (Lock: Avoiding flaky tests with TimeProvider and ITimer, and for when callbacks fire, dotnet/extensions: FakeTimeProvider.cs)

Don't construct it either of these ways:

  • The parameterless constructor starts at midnight on 2000-01-01 UTC, a date the test never states. Pass the start explicitly, even when the test passes at any instant. (Microsoft Learn: FakeTimeProvider constructors)
  • DateTimeOffset.UtcNow as the start brings back the real clock. The test's dates change on every run, and whether it crosses a DST or month boundary depends on when it runs. For the one-clock rule, see testing.md.

For date-sensitive logic, test these instants:

  • A DST spring-forward gap: a local time that doesn't exist.
  • A fall-back overlap: a local time that happens twice.
  • A leap day.
  • A year boundary where the calendar year and the ISO week year differ: 2022-01-02 is in week 52 of 2021.

(Meziantou: 43 Misconceptions about date and time)

For the test framework stack, see testing.md.

UI and hosts

  • Get the user's zone from the browser, not the server. In interactive server Blazor, register a scoped TimeProvider per circuit, filled through JavaScript interop. For the pattern, see ui-frameworks.md.
  • Run hosts in UTC, and convert at the edges. Give each scheduled job an explicit zone. Local time repeats an hour when DST ends and skips one when it starts, so a job set to server-local time in that hour runs twice or not at all. (Microsoft Learn: How to resolve ambiguous times, Microsoft Learn: TimeZoneInfo.IsInvalidTime)
  • Include tzdata in Linux container images, and ICU if you convert between IANA and Windows zone IDs. On Linux, zone conversion needs only tzdata, and ICU serves the ID conversions and any culture other than the invariant one. Windows images include their own zone data and can use NLS for cultures, but the ID conversions still need ICU. For image tags, invariant mode, failure modes, and display formatting, see globalization.md.

Smaller traps

  • TimeSpan.From* has had integer overloads since .NET 9, because the double overloads lose precision: TimeSpan.FromSeconds(101.832) isn't exactly 101.832 seconds. In F#, the new overloads make TimeSpan.FromMinutes(20) ambiguous, so it needs a type annotation. (Microsoft Learn: Breaking change: New TimeSpan.From*() overloads that take integers)
  • TimeZoneInfo.FindSystemTimeZoneById takes the platform's native IDs and needs only tzdata, so it works in invariant globalization mode. TryConvertIanaIdToWindowsId and TryConvertWindowsIdToIanaId need ICU, so they fail in invariant or NLS mode. For details, see globalization.md.