Format durations and ages
Orientation
Call TimeSpan.Humanize for elapsed time and ToAge for a human-readable age approximation. Precision controls how many units appear; minimum and maximum units define the allowed range. Keep calendar-sensitive calculations in date types and use this API only after the application has a duration.
Example
This program shows two-unit precision, locale-aware list punctuation, and an age rendered with number words:
using System.Globalization;
using Humanizer;
var culture = CultureInfo.GetCultureInfo("en-US");
CultureInfo.CurrentCulture = culture;
CultureInfo.CurrentUICulture = culture;
var elapsed = TimeSpan.FromMinutes(125)
.Humanize(precision: 2, culture: culture);
var compact = TimeSpan.FromSeconds(62)
.Humanize(precision: 2, culture: culture, collectionSeparator: null);
var age = TimeSpan.FromDays(750)
.ToAge(culture, toWords: true);
AssertEqual("2 hours, 5 minutes", elapsed);
AssertEqual("1 minute and 2 seconds", compact);
AssertEqual("two years old", age);
Console.WriteLine($"{elapsed}; {age}");
static void AssertEqual(string expected, string actual)
{
if (actual != expected)
throw new InvalidOperationException($"Expected '{expected}', got '{actual}'.");
}
Control the decomposition
precisionlimits the number of returned non-empty units.countEmptyUnits: truecounts gaps after the first non-empty unit toward that limit.maxUnitandminUnitconstrain the decomposition.toWords: truereplaces digits with number words where the locale supports them.collectionSeparator: nulluses the localized collection formatter; any supplied string is used as a literal separator.
The default maximum unit is Week. Ask for Month or Year explicitly when those approximate units are acceptable.
Use ToAge deliberately
ToAge adds the culture’s age phrase to a duration decomposition. It is convenient for an already computed elapsed span, but it is not a birthday calculator.
Pitfall
Months and years are approximated from a duration and do not know calendar month length or leap years. Negative TimeSpan values are rendered with positive unit counts, so preserve direction elsewhere when it matters. A precision of zero or less returns an empty string.
Version notes
TimeSpan.Humanize is available across the documented corpus. ToAge begins
in 3.0.1. The verified executable runs against the selected package; older
snapshots replace or exclude its age call.