Dates, times, and time zones
Four rules cover most cases:
- Use
DateTimeOffsetby default, notDateTime. - Store timestamps in UTC, except future local events.
- Inject
TimeProviderinto services. Never callDateTime.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:
DateTimeOffsetdoesn't know its time zone. It records the offset at one moment, and many zones share an offset. It "can't reflect a time zone's transition to and from daylight saving time". For arithmetic across a DST transition, convert to UTC, calculate there, and convert back withTimeZoneInfo. (Microsoft Learn: Compare types related to date and time, Microsoft Learn: How to use time zones in date and time arithmetic)- A
DateTimewithKind = Unspecifiedis ambiguous, even on the machine that created it. ADateTimethat crosses a boundary must be UTC withKind = Utc. (Microsoft Learn: Compare types related to date and time)
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:
- EF Core 8 and later map
DateOnlyto SQL ServerdateandTimeOnlytotime. (.NET Blog: EF Core 8 Preview 1: Raw, lazy, and on-time) - SQL Server has a
datetimeoffsetcolumn type, and PostgreSQL doesn't: itstimestamptz"does not, in fact, store a time zone in the database, but rather a UTC timestamp". A UTCDateTimeOffsetis portable as an instant, but a non-zero offset isn't: Npgsql writesDateTimeOffsettotimestamptzonly when the offset is 0. (Rojansky: Mapping .NET Timestamps to PostgreSQL) Microsoft.Data.Sqlite10.0 convertsDateTimeOffsetto UTC before writing it to a REAL column. If you target SQLite, check this behaviour change. (Microsoft Learn: EF Core 10 breaking changes)System.Text.Jsonhas round-trippedDateOnlyandTimeOnlysince .NET 7, and writesDateTimeOffsetas ISO 8601 with the offset. Minimal API bodies need no custom converters. A wire format without the offset hands the ambiguity to the client. (Microsoft Learn: DateTime and DateTimeOffset support in System.Text.Json)
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:
Instantfor machine timestamps.LocalDateTimeandDateTimeZonefor what a person enters.ZonedDateTimefor 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()andGetLocalNow(), which returnDateTimeOffset.GetTimestamp()andGetElapsedTime()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/ |
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.UtcNowas 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
TimeProviderper 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 thedoubleoverloads lose precision:TimeSpan.FromSeconds(101.832)isn't exactly 101.832 seconds. In F#, the new overloads makeTimeSpan.FromMinutes(20)ambiguous, so it needs a type annotation. (Microsoft Learn: Breaking change: New TimeSpan.From*() overloads that take integers)TimeZoneInfo.FindSystemTimeZoneByIdtakes the platform's native IDs and needs only tzdata, so it works in invariant globalization mode.TryConvertIanaIdToWindowsIdandTryConvertWindowsIdToIanaIdneed ICU, so they fail in invariant or NLS mode. For details, see globalization.md.