Skip to content
Tutorials Center
My learning

Topics

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.

C#
TimeSpan t = TimeSpan.FromMinutes(90);
Console.WriteLine(t);              // 01:30:00
Console.WriteLine(t.TotalHours);   // 1.5

Try it

C# Creating, reading and combining

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.

C# Formatting, parsing and traps

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

C#
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

  • Minutes is not TotalMinutes. TimeSpan.FromHours(2).Minutes is 0 while TotalMinutes is 120. Use the Total... properties for the overall length.
  • Custom formats need escaping. In ToString(@"hh\:mm") the backslash makes the colon a literal. Without it you get a FormatException. The standard formats c, g and G need no escaping.
  • Default formats. c is the invariant form [-][d.]hh:mm:ss[.fffffff], used by ToString() and Parse. g and G are 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. Use DateTime.AddMonths or DateOnly/DateTimeOffset methods. Daylight saving changes do not affect TimeSpan arithmetic, but they affect local DateTime values.
  • Time of day. A TimeSpan between 00:00 and 24:00 is often used as a time of day, but TimeOnly is the better type since .NET 6.
  • Operators. +, -, unary -, comparison, * and / by a number (.NET Core 3.0+) and / by another TimeSpan (giving a double) all exist.
  • Timers and waits. Task.Delay, Thread.Sleep and CancellationTokenSource.CancelAfter accept a TimeSpan. Use Timeout.InfiniteTimeSpan for "no timeout".
  • Measuring. Use Stopwatch.GetElapsedTime (see num-stopwatch), not DateTime.Now, to measure code, because the clock can change.