Creating robust applications and solutions that can stand the test of time requires using complex dates and timespans to ensure accuracy. C# offers a robust TimeSpan structure that allows developers to easily manipulate dates, durations, and ranges. In this article, we are going to explore how to effectively use the TimeSpan features in C# to help us create dependable solutions without compromising on performance or efficiency.
Let’s get started.
Overview of TimeSpan in C#
TimeSpan
is a value type in C# that represents a time interval and holds the number of ticks (the unit used for measuring time by the CPU) to represent a specific amount of time. Therefore, the TimeSpan
struct helps us measure the number of days, hours, minutes, seconds, and fractions of a second (can be positive or negative).
TimeSpan
values can vary from TimeSpan.MinValue
to TimeSpan.MaxValue
and has several constructors:
Constructor | Description |
---|---|
TimeSpan(Int64) | Instantiates TimeSpan object with a specific number of ticks. |
TimeSpan(Int32, Int32, Int32) | Constructor initializes an instance with a specific number of hours, minutes, and seconds. |
TimeSpan(Int32, Int32, Int32, Int32) | This option instantiates an instance with a specific number of days, hours, minutes, and seconds. |
TimeSpan(Int32, Int32, Int32, Int32, Int32) | Initializes a TimeSpan instance with specific number of days, hours, minutes, seconds, and milliseconds. |
TimeSpan(Int32, Int32, Int32, Int32, Int32, Int32) | This option creates an instance with specific number of days, hours, minutes, seconds, and milliseconds, and microseconds. |
Next, let’s review some of the fields we can use when manipulating TimeSpan
values.
TimeSpan Fields in C#
The TimeSpan
struct has fields that we can use when manipulating values:
Field | Description |
---|---|
MaxValue | The field represents the maximum TimeSpan value. |
MinValue | Represents the minimum TimeSpan value. |
NanosecondsPerTick | This is a constant field that shows the number of nanoseconds per tick. |
TicksPerDay | Shows the number of ticks in one day. |
TicksPerHour | A constant field that shows the number of ticks in one hour. |
TicksPerMicrosecond | The field represents the number of ticks in one microsecond. |
TicksPerMillisecond | Represents the number of ticks in one millisecond. |
TicksPerMinute | Returns the number of ticks in one minute. |
TicksPerSecond | The field represents the number of ticks in one second. |
Zero | Returns the zero TimeSpan value. |
Later, we are going to learn how to use these fields as we implement some examples that use the TimeSpan
struct.
TimeSpan Properties in C#
Also, the TimeSpan
struct has some properties that can help us manipulate TimeSpan
values:
Property | Description |
---|---|
Days | Stores the day component of the TimeSpan structure. |
Hours | Returns the hours component of the TimeSpan structure. |
Microseconds | Gets the component that represents microseconds in a TimeSpan instance |
Milliseconds | Stores the milliseconds component of the TimeSpan structure. |
Minutes | Retrieves the minutes component of the current TimeSpan instance. |
Nanoseconds | This property represents whole nanoseconds. |
Seconds | Represents the seconds component of the TimeSpan structure ranging from -59 to 59. |
Ticks | Represents the number of ticks in the current TimeSpan instance. |
TotalDays | Uses whole and fractional numbers to represent the total number of days in the TimeSpan instance. |
TotalHours | Gets the total number of hours in the current TimeSpan structure. |
TotalMicroseconds | Represents the total number of microseconds in the TimeSpan instance. |
TotalMilliseconds | The property gets the total number of milliseconds in the current instance. |
TotalMinutes | Returns the TimeSpan structure in minutes and uses both whole and fractional values. |
TotalNanoseconds | This property represents whole and fractional nanoseconds. |
TotalSeconds | Returns the value of the current TimeSpan instance as seconds. |
Now that we know some of the properties that the TimeSpan
struct has, let’s learn how to implement some of the methods we can use to manipulate TimeSpan
values.
TimeSpan Methods
The TimeSpan
struct has some useful methods to manipulate TimeSpan
values, which we’ll now look at.
How to Add TimeSpan Objects
Let’s look at how we can add two TimeSpan
values:
var firstTimeSpan = new TimeSpan(1, 60, 3600); var secondTimeSpan = new TimeSpan(2, 60, 3600); var actual = firstTimeSpan.Add(secondTimeSpan); var expected = firstTimeSpan + secondTimeSpan; Assert.AreEqual(expected, actual);
Here, we implement a method that uses the Add()
method and returns a TimeSpan
object. Also, we observe that we can implement the addition operation using the +
operator.
Compare TimeSpan Objects
If we need to compare two TimeSpan
instances to know whether the first value is shorter, equal to, or longer than the second value, we can take advantage of the Compare()
method, which returns zero if the values we are comparing are equal.
Therefore, a value of 1 means the first TimeSpan
value is greater than the second TimeSpan
value. On the other hand, the method returns -1 if the first TimeSpan
value is less than the second TimeSpan
value.
Now, let’s implement an example:
var firstTimeSpan = new TimeSpan(1, 60, 3600); var secondTimeSpan = new TimeSpan(1, 60, 3600); var thirdTimeSpan = new TimeSpan(3, 60, 4000); var equalTo = TimeSpan.Compare(firstTimeSpan, secondTimeSpan); var lessThan = TimeSpan.Compare(secondTimeSpan, thirdTimeSpan); var greaterThan = TimeSpan.Compare(thirdTimeSpan, firstTimeSpan); Assert.AreEqual(0, equalTo); Assert.AreEqual(-1, lessThan); Assert.AreEqual(1, greaterThan);
Here, we prove that the method compares TimeSpan
values accurately.
How to Compare TimeSpan Objects Using the CompareTo() Method
The CompareTo()
method achieves the same purpose as the Compare() method:
var firstTimeSpan = new TimeSpan(1, 60, 3600); var secondTimeSpan = new TimeSpan(1, 60, 3600); var thirdTimeSpan = new TimeSpan(3, 60, 4000); var equalTo = firstTimeSpan.CompareTo(secondTimeSpan); var lessThan = secondTimeSpan.CompareTo(thirdTimeSpan); var greaterThan = thirdTimeSpan.CompareTo(firstTimeSpan); Assert.AreEqual(0, equalTo); Assert.AreEqual(-1, lessThan); Assert.AreEqual(1, greaterThan);
The CompareTo()
method compares the second parameter with the current TimeSpan
instance, and we prove it achieves the same results as our previous example.
Divide Operation With TimeSpan Values in C#
The Divide()
method supports two overloads. Firstly, one allows us to divide the current TimeSpan
instance with another to return a double
object. Meanwhile, the other allows us to divide a TimeSpan
value with a divisor to return a TimeSpan
object.
Without further ado, let’s learn how to implement the first overload of the Divide()
method:
var firstTimeSpan = new TimeSpan(2, 60, 3600); var secondTimeSpan = new TimeSpan(1, 30, 1800); var expected = firstTimeSpan.Divide(secondTimeSpan); var actual = firstTimeSpan / secondTimeSpan; Assert.AreEqual(expected, actual); Assert.IsInstanceOfType(actual, typeof(double)); Assert.IsInstanceOfType(expected, typeof(double));
We can verify that dividing firstTimeSpan
with secondTimeSpan
returns 2.
Now, let’s learn how to divide a TimeSpan
instance with a divisor:
var firstTimeSpan = new TimeSpan(2, 60, 3600); var secondTimeSpan = new TimeSpan(1, 30, 1800); var divisionByMethod = firstTimeSpan.Divide(2); var divisionByOperator = firstTimeSpan / 2; Assert.AreEqual(divisionByMethod, secondTimeSpan); Assert.AreEqual(divisionByOperator, secondTimeSpan); Assert.IsInstanceOfType(divisionByMethod, typeof(TimeSpan)); Assert.IsInstanceOfType(divisionByOperator, typeof(TimeSpan));
Here, we see that dividing the firstTimeSpan
by 2 returns the secondTimeSpan
.
Check the Equality of Two TimeSpan Values
We have a lot of options for checking the equality of TimeSpan
values. First, we can use the Equals()
method to assess whether two TimeSpan
values are equal. Moreover, we can use normal mathematical equality operators to achieve the same result.
Let’s look at how we use it:
var firstTimeSpan = new TimeSpan(1, 60, 3600); var secondTimeSpan = new TimeSpan(1, 60, 3600); var thirdTimeSpan = new TimeSpan(3, 60, 4000); Assert.IsTrue(firstTimeSpan == secondTimeSpan); Assert.IsTrue(firstTimeSpan.Equals(secondTimeSpan)); Assert.IsTrue(firstTimeSpan < thirdTimeSpan); Assert.IsTrue(thirdTimeSpan > secondTimeSpan); Assert.IsTrue(thirdTimeSpan >= secondTimeSpan); Assert.IsTrue(firstTimeSpan <= thirdTimeSpan); Assert.IsTrue(firstTimeSpan != thirdTimeSpan);
Here, we can see that the Equals()
method returns a boolean
value after comparing whether two TimeSpan
values are equal. Also, we see that we can compare TimeSpan
values using operators such as >
, <
, >=
, <=
, !=
, and ==
.
Multiply TimeSpan Values in C#
The Multiply()
method helps us multiply the current TimeSpan
instance with a given factor
to return a TimeSpan
value:
var expected = new TimeSpan(2, 60, 3600); var firstTimeSpan = new TimeSpan(1, 30, 1800); var factor = 2; var multiplyMethod = firstTimeSpan.Multiply(factor); var multiplyOperator = firstTimeSpan * factor; Assert.AreEqual(multiplyMethod, multiplyOperator); Assert.AreEqual(expected, multiplyOperator); Assert.AreEqual(expected, multiplyMethod); Assert.IsInstanceOfType(multiplyMethod, typeof(TimeSpan)); Assert.IsInstanceOfType(multiplyOperator, typeof(TimeSpan));
Here, we prove that our solution returns accurate results and learn that we can use the *
operator to get the same results.
How to Subtract TimeSpan Values in C#
We can use the Subtract()
method when we want to find the difference between the current TimeSpan
and another TimeSpan
value.
var firstTimeSpan = new TimeSpan(2, 60, 3600); var secondTimeSpan = new TimeSpan(1, 30, 1800); var expected = new TimeSpan(1, 30, 1800); var subtractMethod = firstTimeSpan.Subtract(secondTimeSpan); var subtractOperator = firstTimeSpan - secondTimeSpan; Assert.AreEqual(subtractMethod, subtractOperator); Assert.AreEqual(expected, subtractOperator); Assert.AreEqual(expected, subtractMethod); Assert.IsInstanceOfType(subtractMethod, typeof(TimeSpan)); Assert.IsInstanceOfType(subtractOperator, typeof(TimeSpan));
We use the Subtract()
method to get the difference between the two values. However, we can use the -
operator as well to achieve the same result.
Get Absolute Values From TimeSpan Objects
We can utilize the Duration()
method to return the absolute value of the current TimeSpan
instance. So, let’s understand how it works:
var firstTimeSpan = new TimeSpan(2, 60, 3600); var actual = firstTimeSpan.Duration(); var expected = new TimeSpan(04, 00, 00); Assert.AreEqual(actual, expected); Assert.IsInstanceOfType(actual, typeof(TimeSpan));
We convert a TimeSpan
instance to its absolute value and learn that the absolute value of the firstTimeSpan
object is four hours.
Negate TimeSpan Values in C#
In some cases, we may need to negate TimeSpan
values, which we can achieve by making use of the Negate()
method:
var firstTimeSpan = new TimeSpan(2, 60, 3600); var expected = new TimeSpan(-2, -60, -3600); var negateMethod = firstTimeSpan.Negate(); var negateOperator = -(firstTimeSpan); Assert.AreEqual(negateMethod, expected); Assert.AreEqual(negateMethod, negateOperator); Assert.IsInstanceOfType(negateMethod, typeof(TimeSpan));
The method negates each component of the TimeSpan
instance. Also, we learn that we can achieve the same result by using the UnaryNegation technique when assigning a negative TimeSpan
value to negateOperator
.
Create TimeSpan From the Number of Days
We can create a new TimeSpan
object that is accurate to the last millisecond by invoking the FromDays()
method:
var days = 2; var expected = new TimeSpan(46, 60, 3600); var actual = TimeSpan.FromDays(days); var totalDays = actual.TotalDays; Assert.AreEqual(expected, actual); Assert.AreEqual(days, totalDays);
Here, we see that we can create a TimeSpan
object and validate its accuracy by comparing it with the TotalDays
field.
Instantiate TimeSpan From Number of Hours
Likewise, we can create TimeSpan
objects if we know the number of hours using the FromHours()
method:
var hours = 4; var expected = new TimeSpan(2, 60, 3600); var actual = TimeSpan.FromHours(hours); var totalHours = actual.TotalHours; Assert.AreEqual(expected, actual); Assert.AreEqual(hours, totalHours);
Here, we create a TimeSpan
object as we know the number of hours to use. Also, we can use theFromMinutes()
method to create a TimeSpan
instance from the number of minutes.
To create TimeSpan
instances from seconds, milliseconds, microseconds, and ticks, we use the FromSeconds()
, FromMilliseconds()
, MicroSeconds()
, and FromTicks()
methods respectively.
How to Convert TimeSpan Values to Strings
The TimeSpan.ToString()
method allows us to convert the value of the current TimeSpan
instance to its equivalent string
representation.
ToString()
method, check out our great article ToString Method in C#.Now, let’s learn how to invoke this method with a simple example:
var firstTimeSpan = new TimeSpan(2, 60, 3600); var expected = "04:00:00"; var actual = firstTimeSpan.ToString(); Assert.AreEqual(expected, actual); Assert.IsInstanceOfType(actual, typeof(string));
The method takes a TimeSpan
value and returns its string
representation by invoking the TimeSpan.ToString()
method. Now that we’ve covered the methods available to us when working with theTimeSpan
struct, let’s look at some of the common uses.
Common Uses for TimeSpan Objects in C#
TimeSpans come in handy to limit the time a user can spend performing some action. For example, gaming applications use them to limit how long a player has to complete a certain level or challenge before they lose their progress.
Additionally, TimeSpans can help manage applications’ scheduling by setting times when tasks should start and end.
TimeSpans can come in handy in database systems when tracking changes over time or setting limits on how long they store records.
Finally, they provide an easy way to measure durations between events, making them very useful for performance testing and analysis.
Conclusion
The TimeSpan struct is an incredibly useful tool in C# that can provide great flexibility and functionality for applications. By understanding how to create, format, and use TimeSpan objects, we can add valuable features to our programs. Have you used TimeSpans in your code? What tips would you share with other developers? Let us know in the comments below.