C-SHARP - 6.3 TimeSpan

Where DateTime answers "when?", TimeSpan answers "how long?". This structure from the .NET framework represents a duration: an interval between two points in time, or more simply an amount of days, hours, minutes, or seconds. It's the type you'll use to express a wait period, how long a session lasted, or the difference between two dates.

You can create a TimeSpan with a direct constructor, or via the static methods FromDays, FromHours, FromMinutes, FromSeconds, and FromMilliseconds. These helpers make the code much more readable: TimeSpan.FromHours(2.5) unambiguously expresses a duration of two and a half hours. A common operation is subtracting two DateTime values from each other: the result is precisely a TimeSpan.

You access its components through pairs of properties. Days, Hours, Minutes, Seconds return the natural breakdown of the duration. TotalDays, TotalHours, TotalMinutes, TotalSeconds return the full duration expressed in the requested unit, as a double. Reach for the Total* properties whenever you need the whole duration in a single unit (for example, to compute an hourly cost).

TimeSpan values combine naturally through addition and subtraction, and compare with the usual operators. Adding a TimeSpan to a DateTime returns a new DateTime shifted by that amount. This interoperability makes the two types an inseparable pair for handling time in C#.