C# Time Representations

Array Collections File String Windows VB.NET Algorithm ASP.NET Cast Class Compression Convert Data Delegate Directive Enum Exception If Interface Keyword LINQ Loop Method .NET Number Regex Sort StringBuilder Struct Switch Time Value

TimeSpan illustration

Time is not an object. It is not material. It can not be captured. In the C# programming language many objects exist that represent time. DateTime represents a point in time and TimeSpan represents a certain length of time. These types prove useful in programs that exist in the real world.

On the surface, time seems straightforward. Abelson & Sussman, p. 298

DateTime

To get started, this program introduces the DateTime type in the C# language. It creates an instance of a DateTime struct for May 10, 2010. Then, it prints the exact time and date to the screen with Console.WriteLine.

DateTime
Program that uses DateTime [C#]

using System;

class Program
{
    static void Main()
    {
	DateTime val = new DateTime(2010, 5, 10);
	Console.WriteLine(val);
    }
}

Output

5/10/2010 12:00:00 AM

Overview: These C# examples deal with time structs and classes. DateTime, TimeSpan and Timer are included.

Question and answer

Parse. How can you convert a string into its equivalent DateTime representation? You can use one of the many different parsing methods available for this purpose. These articles detail the Parse, ParseExact, TryParse, and TryParseExact methods.

Parse ParseExact TryParse TryParseExact DateTime.Parse SQL DatesFormat illustration

Format. It is important to know how to format DateTime instances when you want to store the DateTime in another representation, such as text. The first article here provides a thorough description of DateTime formatting in the .NET Framework.

DateTime Format pubDate RSS Format DateTime for FilenamesThe current time (now)

Now. One of the most useful properties on the DateTime type is the Now property: this returns the current date and time on the system. The Today property returns the current day with no time information. It is quite appropriate for you to look at these right now.

Now Today

Months and days. This collection of examples deal with using months and days with the DateTime type. You can access the Month property; get all of the days of the week; or store arrays of all months and days.

DateTime.Month Property DayOfWeek Enum Month and Day Arrays

Subtract dates. When you subtract dates, you can sometimes end up with a time period of negative length. In most usages, though, you can find the difference between a later date and an earlier date, which is the elapsed time.

DateTime Subtract Method Days Elapsed From DateTimeProgramming tip

Special values. You can never have a null DateTime instance, because the DateTime is a value type, not a reference type. However, you can use nullable DateTime? instances; and you can also special-case the MinValue in your code—as these articles demonstrate.

DateTime.MinValue: Null Nullable DateTime

FromOADate. If you are dealing with certain Microsoft formats, you may encounter dates stored in double format. You can convert these into actual DateTime instances by using FromOADate, as shown here.

FromOADate and Excel Dates

Advanced formats. Here we show you how to format DateTime values in more complex ways. You can format DateTimes in a "pretty" way that is easily readable, or deal with 24-hour time formats.

Pretty Date Formatting 24-Hour Time Formats

TimeSpan

Next, let's look at a program that uses the TimeSpan type. It first calls the TimeSpan instance constructor twice and then subtracts the second instance from the first instance. This yields the difference between the two TimeSpan instances.

TimeSpan
Program that uses TimeSpan type [C#]

using System;

class Program
{
    static void Main()
    {
	TimeSpan span1 = new TimeSpan(3, 0, 0);
	TimeSpan span2 = new TimeSpan(2, 0, 0);
	// Subtract two hours from three hours.
	TimeSpan span3 = span1.Subtract(span2);
	Console.WriteLine(span3);
    }
}

Output

01:00:00
Note (please read)

Information. Here we see more specific TimeSpan information. You can convert a string into its equivalent TimeSpan representation. This is done by using the TimeSpan.Parse or TimeSpan.TryParse methods. There is also a Zero property on the TimeSpan type.

TimeSpan.Parse and TryParse TimeSpan.Zero Convert TimeSpan to Long

Format uptimes. We detail how you can implement an uptime method by using a format string with TimeSpan instances. This code is implemented to mimic the Windows uptime format.

Uptime TimeSpan Format

TimeZone

.NET Framework information

Continuing on, you can access information about time zones using the C# language and .NET Framework very easily. We more information about this in a set of examples.

TimeZone

Stopwatch

If you need to benchmark a program or part of your program, you can use the Stopwatch type. For some types of programs, using the Stopwatch type to monitor the startup time and ensure it is not too long is useful.

Stopwatch

Timer

With the Timer type, you can create a recurrent event based on an interval of time. The Timer type is really useful for monitoring long-running processes such as websites.

Timer

Performance

Performance optimization

What should you do if DateTime computations are slowing down your program? One solution is to cache DateTime instances: we demonstrate this approach. We also learn about TimeSpan performance.

DateTime Performance Class TimeSpan Performance

Misc.

Miscellaneous

As with other types in the C# language and .NET Framework, you can use the DateTime type in a variety of program contexts. We demonstrate some of these contexts in detail.

Closest Date Sort DateTime List

Summary

The C# programming language

The DateTime type—together with the TimeSpan type—represents time in the C# language and .NET Framework. These types, which are value types and implemented as structs, contain many helper methods which alleviate the pain of having to implement common functionality on each program you develop.

Dot Net Perls