C# TimeSpan


This entry is part 8 of 8 in the series C# Complex Types

TimeSpan represents a length of time, rather than an exact moment in time.

The most simple way to create a TimeSpan object is to use the new operator. There are a few overloads. One of them is hours minutes and seconds. Choose an overload that works for you, remembering that you can simply substitute zeros in if you need to. The number of parameters is 0, 1, 3, 4 and 5, as you can see from the list below. The list of TimeSpan overloads:

  1. empty
  2. long ticks
  3. int hours, int minutes, seconds
  4. int days, int hours, int minutes, seconds
  5. int days, int hours, int minutes, seconds, int milliseconds

There are three ways to create a TimeSpan object. We can use the new operator. The second way is to use the static methods on the TimeSpan structure. They all start with From. If you have two DateTime objects and you subtract them, the result is a TimeSpan.

using System;
namespace TimeSpanExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creating TimeSpan object - there are 3 ways.
            var timeSpan = new TimeSpan(1, 2, 3);  // hours minutes seconds
            var timeSpan1 = new TimeSpan(1, 0, 0);  // one hour
            // second way:
            var timeSpan2 = TimeSpan.FromHours(1);  // easier to know it is one hour
            // third way:
            var now = DateTime.Now;
            var end = DateTime.Now.AddMinutes(2);
            var duration = end - now;
            Console.WriteLine("Duration: " + duration);
            // above result is: Duration: 00:02:00.00199797
            var negativeduration = now - end;
            Console.WriteLine("\"Negative Duration\": " + duration);  // positive number

            TimeSpan trueEnd = now.AddMinutes(2) - now; // need to subtract to get TimeSpan object
            Console.WriteLine("True Duration: " + trueEnd);
            // above output: True Duration: 00:02:00
        }
    }
}

Properties

Once we have created a TimeSpan object we can easily read its Properties. Suppose you wanted to get the Hours. There are two properties to choose from: Hours and TotalHours. Why? What’s the difference?

The Total group of properties converts the entire TimeSpan into whatever unit you specify in the property. So, one hour, 2 minutes and 3 seconds converts to 62.05 minutes. The type is double. The Minutes property, for example, just returns the number of minutes, which is 2 in our example.

Methods

There are two methods of TimeSpan: Add() and Subtract(). Since TimeSpan is immutable/unchangeable, we use these methods to create a new TimeSpan. The Add() method takes a parameter of type TimeSpan. We can use the new operator or one of the static methods.

Conversions

If you want to convert a TimeSpan to a string you simply use the ToString() method. Note that Console.WriteLine() will automatically convert anything passed into it to a string. You do not need to explicitly convert to a string. If you do add the ToString() method in Console.WriteLine you will notice that it is greyed out. However, if you are not using Console.WriteLine (or Console.Write) you will need to know how to use the ToString() method if you need to convert it to a string. You can use the Parse() method to convert a string to a TimeSpan. In the last line of code it is converted back to a string by the Console.WriteLine method.

Below is all of our code for this post.

using System;
namespace TimeSpanExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creating TimeSpan object - there are 3 ways.
            var timeSpan = new TimeSpan(1, 2, 3);  // hours minutes seconds
            var timeSpan1 = new TimeSpan(1, 0, 0);  // one hour
            // second way:
            var timeSpan2 = TimeSpan.FromHours(1);  // easier to know it is one hour
            // third way:
            var now = DateTime.Now;
            var end = DateTime.Now.AddMinutes(2);
            var duration = end - now;
            Console.WriteLine("Duration: " + duration);
            // above result is: Duration: 00:02:00.00199797
            var negativeduration = now - end;
            Console.WriteLine("\"Negative Duration\": " + duration);  // positive number

            TimeSpan trueEnd = now.AddMinutes(2) - now; // need to subtract to get TimeSpan object
            Console.WriteLine("True Duration: " + trueEnd);
            // above output: True Duration: 00:02:00

            // Properties
            // timeSpan is one hour, two minutes and 3 seconds (see above)
            Console.WriteLine("Minutes: " + timeSpan.Minutes);
            Console.WriteLine("Total Minutes: " + timeSpan.TotalMinutes);
            Console.WriteLine("Total Days: " + timeSpan.TotalDays);

            // Add Method of TimeSpan
            // let's add 3 minutes to our original TimeSpan of 1 hour 2 minutes 3 seconds
            Console.WriteLine("Add 3 minutes: " + timeSpan.Add(TimeSpan.FromMinutes(3)));
            Console.WriteLine("Add 4 minutes: " + timeSpan.Add(new TimeSpan(0,4,0)));

            // ToString method
            Console.WriteLine("ToString: " + timeSpan.ToString());
            Console.WriteLine("ToString not needed: " + timeSpan); // don't need ToString here

            // Parse method
            Console.WriteLine("Parse: " + TimeSpan.Parse("01:02:03"));

        }
    }
}
Series Navigation<< C# Date and Time