BlackWaspTM
.NET Framework
.NET 1.1+

DateTime Data Type (2)

The twenty-fifth part of the C# Fundamentals tutorial starts an examination of the DateTime data type. The structure allows storage and manipulation of date and time information with a range of thousands of years but accuracy in fractions of microseconds.

String Parsing

When accepting a date entered by a user, it can be difficult to ensure that the correct format is used, particularly for international applications where users in different countries have varying date formats. The Parse method converts strings to DateTime values using local date formats. The example below assumes the use of a UK-configured computer.

DateTime newDate;

newDate = DateTime.Parse("01/02/2006");         // Date = 1 Feb 2006 (midnight)
newDate = DateTime.Parse("02/01/2000 03:04");   // Date = 2 Jan 2000 03:04:00
newDate = DateTime.Parse("02/01/06");           // Date = 2 Jan 2006 (midnight)

NB: There are various overloaded variations of the Parse method that give finer control over the conversion of strings. There is also another method named ParseExact. These are beyond the scope of the C# Fundamentals tutorial.

Assigning the Current Date and Time

The DateTime structure provides three static properties that return the current date or time. The Now property returns the current local date and time. If you only need the date you can use the Today property, which defaults the time to midnight. Finally, when storing times using Co-ordinated Universal Time, the UtcNow property provides the correct UTC date and time.

DateTime newDate;

newDate = DateTime.Now;                         // Current local time
newDate = DateTime.Today;                       // Current local date (midnight)
newDate = DateTime.UtcNow;                      // Current UTC time

MinValue and MaxValue

The last manner to be considered for creating a DateTime value is to use one of two predefined values. These are retrieved from the static properties MinValue or MaxValue. These properties return the minimum or maximum possible DateTime values and are usually used to indicate that a date is undefined where the use of null is not permitted.

DateTime newDate;

newDate = DateTime.MinValue;                    // 01/01/0001 00:00:00
newDate = DateTime.MaxValue;                    // 31/12/9999 23:59:59

.NET 2.0 Nullable DateTime

Earlier in the tutorial we examined the nullable numeric data types that were introduced as part of the .NET Framework 2.0. The DateTime data type has a nullable equivalent with similar functionality.

DateTime? nullableDate;

nullableDate = DateTime.MinValue;               // Assign a non-null date
nullableDate = null;                            // Assign an undefined value
20 December 2006