Developer

Calculate period of time with .NET

The inclusion of multiple time and date values in development projects often results in the need to calculate a difference. Learn how to complete this task with .NET's TimeSpan value type.

A common feature of most development projects is the utilization of date and time values. You may utilize this feature in a variety of places, including report generation, data entry, and calculations. The inclusion of multiple time and date values often results in the need to calculate a difference. The .NET Framework provides numerous approaches to this type of problem. In this article, I'll focus on the TimeSpan value type with examples of using it in your code.

What is a DateTime?

The Microsoft documentation states that a DateTime value type represents dates and times with values ranging from 12:00:00 midnight, Jan. 1, 0001 Anno Domini (Common Era) to 11:59:59 P.M., Dec. 31, 9999 A.D. (C.E.). So, you may use the DateTime value type to work with any date and time imaginable. A DateTime value represents a specific instance in time. The following C# code establishes a DateTime object for April 1, 2004:

DateTime dt = new DateTime(2004, 4, 1);

The J# syntax is the same. The VB.NET equivalent appears next:

Dim dt As DateTime = DateTime(2004, 4, 1)

This simple example demonstrates one of the DateTime constructors. In total, there are seven constructors. One of the most basic constructors accepts a lone number representing ticks. Microsoft defines a tick as the smallest unit of time that can be specified; it's equal to 100 nanoseconds. Both the specification of a number of ticks and the value of a TimeSpan can be positive or negative.

Dealing with a time span

Developers may use a TimeSpan value type to calculate the difference between two DateTime values; the difference returns in ticks. The calculated value represents a period of time, and it may be formatted for display using the basic .NET formatting syntax. One note on the formatting is that the largest unit of time that you can use to display a TimeSpan value is a day because the number of days in months and years varies. The following C# example returns the difference between two DateTime values:

try {
DateTime dt1 = DateTime.Now;
DateTime dt2 = new DateTime(2003,4,15);
TimeSpan ts = dt1.Subtract(dt2);
Console.WriteLine(ts);
} catch (Exception ex) {
Console.WriteLine(ex.Message);
}

The example generates the following output:

349.14:32:44.1937760

Here are the components of the output:

  • 349 days
  • 14 hours
  • 32 minutes
  • 44 seconds
  • 1937760 milliseconds

There are properties available to easily access each value.

Working with TimeSpan results

The TimeSpan value type contains various properties and methods for accessing or manipulating a TimeSpan's value. The following list contains a selection of these items:

  • Add: Add another TimeSpan to it.
  • Days: Return the day portion of the TimeSpan value.
  • Duration: Retrieve the absolute value of the TimeSpan.
  • Hours: Return the hour portion of the TimeSpan value.
  • Milliseconds: Return the millisecond portion of the TimeSpan value.
  • Minutes: Return the minute portion of the TimeSpan value.
  • Negate: Retrieve the negated value of the current instance.
  • Seconds: Return the second portion of the TimeSpan value.
  • Subtract: Subtract another TimeSpan from it.
  • Ticks: Return the TimeSpan value as ticks.
  • TotalDays: Return the TimeSpan value as days.
  • TotalHours: Return the TimeSpan value as hours.
  • TotalMilliseconds: Return the TimeSpan value as milliseconds.
  • TotalMinutes: Return the TimeSpan value as minutes.
  • TotalSeconds: Return the TimeSpan value as seconds.

The following C# code shows a portion of these items in action. The TimeSpan object is created with specific parameters to match the value generated in the previous example:

TimeSpan ts = new TimeSpan(349,14,32,44,1937760);
Console.WriteLine(ts);
Console.WriteLine("Days: " + ts.Days);
Console.WriteLine("Hours: " + ts.Hours);
Console.WriteLine("Minutes: " + ts.Minutes);
Console.WriteLine("Seconds: " + ts.Seconds);
Console.WriteLine("Milliseconds: " + ts.Milliseconds);
Console.WriteLine("Ticks: " + ts.Ticks);
Console.WriteLine("Total days: " + ts.Days);
Console.WriteLine("Total hours: " + ts.Hours);
Console.WriteLine("Total minutes: " + ts.Minutes);
Console.WriteLine("Total seconds: " + ts.Seconds);
Console.WriteLine("Total milliseconds: " + ts.Milliseconds);

The output shows what each method or property returns:

349.15:05:01.7600000
Days: 349
Hours: 15
Minutes: 5
Seconds: 1
Milliseconds: 760
Ticks: 302079017600000
Total days: 349
Total hours: 15
Total minutes: 5
Total seconds: 1
Total milliseconds: 760

Notice the tick value in the output; it's a very large number. This is due to the fact that ticks start with the beginning of the TimeSpan range of values: Jan. 1, 0001. The example code is identical in J#. The VB.NET equivalent appears next:

Dim ts As New TimeSpan(349, 14, 32, 44, 193)
Console.WriteLine(ts)
Console.WriteLine("Days: " + ts.Days.ToString)
Console.WriteLine("Hours: " + ts.Hours.ToString)
Console.WriteLine("Minutes: " + ts.Minutes.ToString)
Console.WriteLine("Seconds: " + ts.Seconds.ToString)
Console.WriteLine("Milliseconds: " + ts.Milliseconds.ToString)
Console.WriteLine("Ticks: " + ts.Ticks.ToString)
Console.WriteLine("Total days: " + ts.Days.ToString)
Console.WriteLine("Total hours: " + ts.Hours.ToString)
Console.WriteLine("Total minutes: " + ts.Minutes.ToString)
Console.WriteLine("Total seconds: " + ts.Seconds.ToString)
Console.WriteLine("Total milliseconds: " + ts.Milliseconds.ToString)

Why use TimeSpan?

You may be wondering why TimeSpan is included in the .NET Framework, since you can achieve similar functionality with DateTime objects or other means. As with most development endeavors, there is often more than one solution to a problem. The powerful aspect of TimeSpan is that it returns absolute values in days, and this type of value is often required.

TechRepublic's free .NET newsletter, delivered each Wednesday, contains useful tips and coding examples on topics such as Web services, ASP.NET, ADO.NET, and Visual Studio .NET. Automatically sign up today!

About

Tony Patton has worn many hats over his 15+ years in the IT industry while witnessing many technologies come and go. He currently focuses on .NET and Web Development while trying to grasp the many facets of supporting such technologies in a productio...

0 comments

Editor's Picks