| id | relative-dates-and-times |
|---|---|
| title | Humanize relative dates and times |
| sidebar_position | 7 |
| diataxis | how-to |
| persona | application developer |
import CodeBlock from '@theme/CodeBlock'; import dates from '!!raw-loader!../_examples/scenarios-dates/Program.cs';
Relative humanization compares a temporal value with a known base and returns text such as yesterday, 3 hours ago, or a month from now. Pass both the comparison base and culture when output must be deterministic. Choose the overload that preserves the semantics of DateTime, DateTimeOffset, DateOnly, or TimeOnly.
The example compares two UTC DateTime values and never reads the machine clock:
{dates}
| Type | Comparison meaning |
|---|---|
DateTime |
Local or UTC behavior selected by utcDate and Kind |
DateTimeOffset |
Two offset-aware instants |
DateOnly |
Calendar dates without a time of day |
TimeOnly |
Times of day without a calendar date |
Nullable overloads return the locale’s “never” phrase for null. That is useful for optional activity timestamps but should not replace explicit missing-value handling in domain logic.
The default strategies choose familiar boundaries such as “yesterday.” PrecisionDateTimeHumanizeStrategy and its sibling strategies use a precision factor when applications need more gradual thresholds. Assign a strategy through Configurator once during startup.
Do not compare a local DateTime with a UTC base accidentally. Humanizer converts the injected comparison according to utcDate; mixed Kind values can move the boundary. TimeOnly has no date context, so a comparison around midnight cannot know whether the intended event was yesterday or tomorrow.
DateTime and DateTimeOffset support span the documented corpus. DateOnly and TimeOnly humanization begin in 2.11.10 on compatible target frameworks. Strategy types and thresholds are selected-version behavior.