TimeSpan Multiplication and Division
The TimeSpan structure is great for storing a period of time that can be expressed in small values, such as milliseconds or ticks, as well as large durations such as months and years. Unfortunately the structure does not directly support multiplication.
Conversion to Ticks
It is often seen as an omission of the .NET framework that the TimeSpan structure does not directly support multiplication and division using standard arithmetic operators. Although multiplying two TimeSpans would be nonsensical, multiplying a duration by an integer or floating point value is a common task.
In order to multiply or divide a TimeSpan with a simple number, the TimeSpan value must first be converted to an integer value. The best solution is to determine the number of ticks that the TimeSpan represents. A tick is the smallest quantity of time that Microsoft Windows recognises. Once the tick value is held in an integer, it may be multiplied or divided. The resultant value can then be converted back into a TimeSpan to obtain the desired final result.
To convert a TimeSpan to a tick value, the Ticks property of the structure is read. This returns a 64-bit long integer. To return the processed value to a TimeSpan, the static FromTicks method is used. The following example demonstrates this by multiplying one hour and five minutes by twelve to obtain the correct result of thirteen hours.
TimeSpan duration = new TimeSpan(1, 5, 0);
duration = TimeSpan.FromTicks(duration.Ticks * 12);
Console.WriteLine(duration); // Outputs "13:00:00"
10 February 2008