Glossary / TimeSpan
TimeSpan
TimeSpan represents a duration or elapsed-time interval as ticks, with convenience properties for days, hours, minutes, seconds, and milliseconds. It is not a date, time zone, or calendar period; month/year durations require calendar rules and should not be approximated as fixed numbers of days.
Construction and arithmetic
TimeSpan timeout = TimeSpan.FromSeconds(5);
DateTimeOffset deadline = DateTimeOffset.UtcNow + timeout;
A TimeSpan can be negative and has a finite range. TotalSeconds includes fractional units, while Seconds returns only the seconds component within the time portion; confusing component properties with total properties causes bugs. Arithmetic can overflow; checked operations or range validation may be appropriate. Parsing and formatting can be culture-sensitive; use invariant formats for protocols.
Use Stopwatch for measuring elapsed performance because wall clocks can move due to synchronization or user changes. Use TimeProvider in modern .NET for testable time-dependent logic and delays where supported.
Interview questions
- TimeSpan vs DateTime? Duration versus a date/time value.
SecondsvsTotalSeconds? Component 0–59-like portion versus full duration in seconds.- Why Stopwatch for benchmarking? It uses a monotonic timer suitable for elapsed measurement.
- Does one month equal 30 days? Not generally; calendar periods need date/time-zone rules.
- Can TimeSpan be negative? Yes.