TimeSpan
This .NET type represents a length of time. We can create or manipulate TimeSpan
instances—TimeSpan
provides many properties and methods.
TimeSpan
is implemented as a struct
type. We use its many constructors to specify a new TimeSpan
. We can add TimeSpans
, or subtract them to get elapsed times.
First we use the TimeSpan
instance constructor to create TimeSpan
structs. This constructor has several parameters and overloaded versions.
TimeSpan
constructor with 5 int
arguments. The code creates a TimeSpan
with 1 day, 2 hours, and 1 minute.using System; // Use TimeSpan constructor. // ... Use days, hours, minutes, seconds, milliseconds. TimeSpan span = new TimeSpan(1, 2, 1, 0, 0); Console.WriteLine(span);1.02:01:00
The TimeSpan
type has several public static
methods that start with the word From. These include FromDays
, FromHours
, FromMinutes
, FromSeconds
, and FromMilliseconds
.
double
type into a TimeSpan
struct
instance.TimeSpan
result will allow you to use the figure in a more natural way in C# programs and other methods.using System; // Get time spans from a specific double unit of time. // ... These allow easier manipulation of the time. TimeSpan span1 = TimeSpan.FromDays(1); TimeSpan span2 = TimeSpan.FromHours(1); TimeSpan span3 = TimeSpan.FromMinutes(1); TimeSpan span4 = TimeSpan.FromSeconds(1); TimeSpan span5 = TimeSpan.FromMilliseconds(1); Console.WriteLine(span1); Console.WriteLine(span2); Console.WriteLine(span3); Console.WriteLine(span4); Console.WriteLine(span5);1.00:00:00 01:00:00 00:01:00 00:00:01 00:00:00.0010000
Here we use the Add instance method. The TimeSpan.Add
method receives one parameter of type TimeSpan
. When we add one minute to two minutes, we get three minutes.
TimeSpan
are immutable and you can assign the result of the Add method to another TimeSpan
variable.using System; // Adds a TimeSpan of one minute to a TimeSpan of two minutes. // ... Then we get three minutes in a TimeSpan. TimeSpan span1 = TimeSpan.FromMinutes(1); TimeSpan span2 = TimeSpan.FromMinutes(2); TimeSpan span3 = span1.Add(span2); Console.WriteLine(span3);00:03:00
This method receives one TimeSpan
. The argument is the TimeSpan
you want to subtract. Typically, you will subtract the smaller TimeSpan
from the larger TimeSpan
.
using System; // Subtract TimeSpan of one second from one minute. // ... The result is 59 seconds. TimeSpan span1 = TimeSpan.FromMinutes(1); TimeSpan span2 = TimeSpan.FromSeconds(1); TimeSpan span3 = span1.Subtract(span2); Console.WriteLine(span3);00:00:59
MaxValue
, MinValue
We see the value returned when you access the MaxValue
and MinValue
fields, which are public static
readonly
fields.
MaxValue
is equal to over ten million days. The MinValue
is equal to negative ten million days.using System; // Write the maximum, minimum and zero values for TimeSpan. Console.WriteLine(TimeSpan.MaxValue); Console.WriteLine(TimeSpan.MinValue); Console.WriteLine(TimeSpan.Zero);10675199.02:48:05.4775807 -10675199.02:48:05.4775808 00:00:00
TicksPer
constantsWe look at the values of the TicksPerDay
, TicksPerHour
, TicksPerMinute
, TicksPerSecond
, and TicksPerMillisecond
constants.
TimeSpan
type.using System; // Write the values for these Ticks Per constants. Console.WriteLine(TimeSpan.TicksPerDay); Console.WriteLine(TimeSpan.TicksPerHour); Console.WriteLine(TimeSpan.TicksPerMinute); Console.WriteLine(TimeSpan.TicksPerSecond); Console.WriteLine(TimeSpan.TicksPerMillisecond);864000000000 36000000000 600000000 10000000 10000
You can use this static
method on the TimeSpan
type. This method takes the TimeSpan
instance and converts it to the absolute value of itself.
TimeSpan
, this method will make the TimeSpan
positive.using System; // Use the TimeSpan Duration method. // ... This converts negative TimeSpans into positive TimeSpans. // ... Same as absolute value of the time. TimeSpan span = new TimeSpan(-1, -1, -1); TimeSpan duration = span.Duration(); Console.WriteLine(duration);01:01:01
TotalHours
Here we demonstrate the difference between the Hours instance property on TimeSpan
, and the TotalHours
instance property.
TotalSeconds
, and Days and TotalDays
.TimeSpan
that indicates hours. This is only a part of the entire time represented.TotalHours
property returns the entire time represented converted to a value represented in hours.using System; // Shows the TimeSpan constructor, Hours and TotalHours. // ... Hours is only a part of the time. // ... TotalHours converts the entire time to hours. TimeSpan span = new TimeSpan(0, 500, 0, 0, 0); Console.WriteLine(span.Hours); Console.WriteLine(span.TotalHours);20 500
The TimeSpan.Zero
field is a public static
field and it provides the exact representation of no time. This is useful because we cannot set a TimeSpan
to zero in any other way.
using System; // Demonstrate TimeSpan zero. TimeSpan span = TimeSpan.Zero; Console.WriteLine(span); Console.WriteLine(span.TotalMilliseconds);00:00:00 0
When you access the TimeSpan.Zero
field, the "load static
field" instruction is executed. This pushes the value onto the evaluation stack.
TimeSpan.Zero
field is initialized in a static
constructor in the TimeSpan
type.TimeSpan
constructor where the argument is a long value of ticks. The argument 0L is used. This is zero in long format.TimeSpan
(long) constructor, the field of name "_ticks" is assigned to the parameter. TimeSpan.Zero
equals "new TimeSpan
(0)".static TimeSpan() { Zero = new TimeSpan(0L); MaxValue = new TimeSpan(9223372036854775807L); MinValue = new TimeSpan(-9223372036854775808L); }
Parse
, TryParse
These methods are useful when reading in TimeSpans
that may have been persisted as strings to files. The Parse
and TryParse
methods have similar internal logic.
TryParse
is safer and faster for when you may encounter errors in the data, and it is usually better to use for this case.string
. It specifies a span with zero hours, zero minutes, and one second.TryParse
on an invalid time span string
. This causes no exception to be thrown.using System; // Use TimeSpan.Parse method to parse in span string. // ... Write it to the console. TimeSpan span = TimeSpan.Parse("0:00:01"); Console.WriteLine(span); // Use TimeSpan.TryParse to try to parse an invalid span. // ... The result is TimeSpan.Zero. TimeSpan span2; TimeSpan.TryParse("X:00:01", out span2); Console.WriteLine(span2);00:00:01 00:00:00
string
A TimeSpan
can be formatted to a string
with a format string
. We can use codes like hh, mm and ss. We often must escape the ":" chars.
TimeSpan
of 3 hours, 30 minutes. We format it with an hours: minutes: seconds format.using System; // Represents three hours and thirty minutes. TimeSpan threeHours = new TimeSpan(3, 30, 0); // Write hours, minutes and seconds. Console.WriteLine("{0:hh\\:mm\\:ss}", threeHours);03:30:00
TimeSpan
Usually TimeSpan
instances are not a performance concern. But for completeness, we test 3 different ways of acquiring TimeSpan
instances.
TimeSpan
with its FromHours
method.TimeSpan
constructor with 3 arguments to create a new TimeSpan
instance.TimeSpan
but assumes a cached TimeSpan
is available and references that.TimeSpan.FromHours
has been optimized to be closer in performance to the other 2 versions.using System; using System.Diagnostics; const int m = 100000000; Stopwatch s1 = Stopwatch.StartNew(); // Version 1: use FromHours. for (int i = 0; i < m; i++) { TimeSpan span = TimeSpan.FromHours(1); } s1.Stop(); Stopwatch s2 = Stopwatch.StartNew(); // Version 2: use TimeSpan constructor. for (int i = 0; i < m; i++) { TimeSpan span = new TimeSpan(1, 0, 0); } s2.Stop(); Stopwatch s3 = Stopwatch.StartNew(); // Version 3: use cached TimeSpan. TimeSpan cache = new TimeSpan(1, 0, 0); for (int i = 0; i < m; i++) { TimeSpan span = cache; } s3.Stop(); Console.WriteLine("{0},{1},{2}", s1.ElapsedMilliseconds, s2.ElapsedMilliseconds, s3.ElapsedMilliseconds);TimeSpan.FromHours(1): 45 ms new TimeSpan(1, 0, 0): 33 ms Cache: 33 ms
The Sleep()
method can be called with a TimeSpan
argument. To sleep for 3 seconds, we can use TimeSpan.FromSeconds
with an argument of 3.
TimeSpan
, which represents time periods, has many aspects. This struct
type is a useful representation of periods of time in your programs.