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

  1. TimeSpan vs DateTime? Duration versus a date/time value.
  2. Seconds vs TotalSeconds? Component 0–59-like portion versus full duration in seconds.
  3. Why Stopwatch for benchmarking? It uses a monotonic timer suitable for elapsed measurement.
  4. Does one month equal 30 days? Not generally; calendar periods need date/time-zone rules.
  5. Can TimeSpan be negative? Yes.

References