C# Reference ยท Date, Time and Globalization
TimeSpan in depth
Reference for System.TimeSpan in C#: creating durations, the difference between Hours and TotalHours, arithmetic, parsing, and custom format strings.
TimeSpan represents a length of time: the difference between two moments, a timeout, a delay or an elapsed time. It is a struct that stores a signed count of 100-nanosecond ticks, so it can be negative and can span many days (about 29,000 years in each direction).
The most common mistake is mixing up the component properties (Hours, Minutes) with the Total... properties. A span of 1 day and 3 hours has Hours == 3 but TotalHours == 27.
var d = TimeSpan.FromMinutes(90); Console.WriteLine(d.Hours + " h, " + d.TotalMinutes + " min"); // 1 h, 90 min
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public readonly struct TimeSpan : IComparable<TimeSpan>, IEquatable<TimeSpan>, IFormattable, IParsable<TimeSpan>
new TimeSpan(long ticks) new TimeSpan(int hours, int minutes, int seconds) new TimeSpan(int days, int hours, int minutes, int seconds) new TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds) new TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds, int microseconds)
| Member | Description |
|---|---|
Days, Hours, Minutes, Seconds, Milliseconds, Microseconds, Nanoseconds |
The component of the span (hours is 0 to 23, and so on, with the sign of the span). |
TotalDays, TotalHours, TotalMinutes, TotalSeconds, TotalMilliseconds |
The whole span expressed as a double in that unit. |
Ticks |
The raw long; TicksPerSecond is 10,000,000. |
FromDays, FromHours, FromMinutes, FromSeconds, FromMilliseconds, FromMicroseconds, FromTicks |
Static factories (double overloads; integer overloads were added in .NET 9). |
Add, Subtract, Multiply, Divide, Negate, Duration and the operators + - * / |
Arithmetic. Duration() is the absolute value. |
Parse, TryParse, ParseExact, TryParseExact |
Text to span. |
ToString(), ToString(string, IFormatProvider) |
Standard formats "c" (default), "g", "G"; custom specifiers d, h, m, s, f, F. |
Zero, MinValue, MaxValue |
Constants. |
Errors: constructors and factories throw OverflowException when the result is outside the long range of ticks. FromSeconds(double.NaN) throws ArgumentException. Parse throws FormatException or OverflowException (for example ParseExact("90", "%m", ...) overflows, because the minute part must be 0 to 59). Duration() and Negate() throw OverflowException for MinValue. Dividing a span by TimeSpan.Zero gives infinity (a double); dividing it by the number zero throws OverflowException.
Usage notes
Hoursis notTotalHours. UseTotal...for "how long in this unit" and the component properties only when you display days, hours and minutes separately.- Colons and slashes must be escaped in custom format strings:
"hh':'mm"or@"hh\:mm". An unescaped:throwsFormatException. Custom formats do not support a minus sign; add it yourself for negative spans. - Default string form is
[-][d.]hh:mm:ss[.fffffff], independent of culture, which is whyToString()is safe for logs. - Precision. The smallest unit is one tick (100 ns). The
doublefactories such asFromSeconds(0.1)start from a binary floating-point number, so very fractional input can be off by a tick; use ticks or the integer overloads (.NET 9) when you need exact values. - A
TimeSpanis a duration, not a clock time. Do not use it to hold "09:00 each day" when you also add it to dates across daylight saving changes; useTimeOnlyfor that. - Calendar months and years are not durations. There is no
FromMonths, because months have different lengths. UseAddMonthson a date. - Timeouts. APIs such as
Task.Delay,CancellationTokenSourceandProcess.WaitForExitaccept spans.Timeout.InfiniteTimeSpan(-1 ms) means no timeout. - Measuring elapsed time: use
StopwatchorTimeProvider.GetElapsedTime, not differences ofDateTime.Now, which can jump when the clock is adjusted.