C# Reference ยท Numbers and Math
C# TimeSpan struct
Reference for the C# TimeSpan struct: create durations, read Total and component properties, do arithmetic, parse and format them, and avoid common traps.
TimeSpan represents a length of time: 90 minutes, 2.5 seconds, minus 3 days. It is a struct that stores a signed count of ticks, where one tick is 100 nanoseconds. A TimeSpan is a duration, not a point on the calendar; subtracting two DateTime values gives one, and adding one to a DateTime moves it forward in time.
The range is about ยฑ29,000 years. A TimeSpan does not know about months or years, because those have varying lengths. Its largest unit is the day.
TimeSpan t = TimeSpan.FromMinutes(90); Console.WriteLine(t); // 01:30:00 Console.WriteLine(t.TotalHours); // 1.5
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 TimeSpan(long ticks) public TimeSpan(int hours, int minutes, int seconds) public TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds = 0, int microseconds = 0) public static TimeSpan TimeSpan.FromDays(double value) // also FromHours, FromMinutes, FromSeconds, FromMilliseconds, FromMicroseconds, FromTicks public static TimeSpan TimeSpan.Parse(string s, IFormatProvider? provider = null) public static bool TimeSpan.TryParse(string? s, out TimeSpan result) public static TimeSpan TimeSpan.ParseExact(string input, string format, IFormatProvider? provider) public static readonly TimeSpan TimeSpan.Zero, MinValue, MaxValue public double TotalDays, TotalHours, TotalMinutes, TotalSeconds, TotalMilliseconds { get; } public int Days, Hours, Minutes, Seconds, Milliseconds { get; } public long Ticks { get; } public TimeSpan Duration() public TimeSpan Negate()
| Name | Description |
|---|---|
ticks |
Count of 100-nanosecond units. TimeSpan.TicksPerSecond is 10,000,000. |
Days ... Milliseconds |
Components of the value: hours 0โ23, minutes and seconds 0โ59, milliseconds 0โ999. |
TotalXxx |
The whole value expressed in that unit as a fractional double. |
Duration() |
The absolute value. Throws OverflowException for TimeSpan.MinValue. |
Returns: a TimeSpan for the constructors, From..., arithmetic and parsing; TryParse returns bool.
Errors: OverflowException when an operation leaves the range; FormatException from Parse and ParseExact; ArgumentException for non-finite values such as FromSeconds(double.NaN).
Usage notes
Minutesis notTotalMinutes.TimeSpan.FromHours(2).Minutesis0whileTotalMinutesis120. Use theTotal...properties for the overall length.- Custom formats need escaping. In
ToString(@"hh\:mm")the backslash makes the colon a literal. Without it you get aFormatException. The standard formatsc,gandGneed no escaping. - Default formats.
cis the invariant form[-][d.]hh:mm:ss[.fffffff], used byToString()andParse.gandGare culture-sensitive forms, but the runner here is invariant. - Precision.
FromSeconds(double)and related methods round to the nearest tick in modern .NET, while very old frameworks rounded to the nearest millisecond. Prefer integer ticks if you need exact storage. - Not for calendar arithmetic. "One month later" is not a
TimeSpan. UseDateTime.AddMonthsorDateOnly/DateTimeOffsetmethods. Daylight saving changes do not affectTimeSpanarithmetic, but they affect localDateTimevalues. - Time of day. A
TimeSpanbetween 00:00 and 24:00 is often used as a time of day, butTimeOnlyis the better type since .NET 6. - Operators.
+,-, unary-, comparison,*and/by a number (.NET Core 3.0+) and/by anotherTimeSpan(giving adouble) all exist. - Timers and waits.
Task.Delay,Thread.SleepandCancellationTokenSource.CancelAfteraccept aTimeSpan. UseTimeout.InfiniteTimeSpanfor "no timeout". - Measuring. Use
Stopwatch.GetElapsedTime(seenum-stopwatch), notDateTime.Now, to measure code, because the clock can change.
Related
num-stopwatchnum-mathandnum-tostringtime-datetimeandtime-timespan- Tutorial: Dates and times