BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET Framework
.NET 1.1+

DateTime Information Extraction

The twenty-sixth part of the C# Fundamentals tutorial continues the examination of the DateTime data type provided by C# and the .NET Framework. In this instalment we will consider how information can be compared and extracted from values of this type.

DateTime Comparison

Equality and Inequality Operators

Throughout the C# Fundamentals tutorial the equality (==) and inequality (!=) operators have been used to compare values. These operators can be used with the DateTime data type in the same manner as for any other value type.

DateTime startDate = DateTime.Parse("30 Dec 2006");
DateTime endDate = DateTime.Parse("1 Jan 2007");
DateTime targetDate = DateTime.Parse("1 Jan 2007");
bool result;

result = startDate == endDate;		// result = false
result = targetDate == endDate;		// result = true
result = startDate != endDate;		// result = true
result = targetDate != endDate;		// result = false

Comparison Operators

The DateTime data type holds information that supports the concept of ordering. This means that, as with the numeric data types, it is possible to use comparison operators to determine which of two operands is the greater (or in the case of date and time information, the later). As with numeric data, the available operators are greater than (>), less than (<), greater than or equal to (>=) and less than or equal to (<=).

DateTime startDate = DateTime.Parse("30 Dec 2006");
DateTime endDate = DateTime.Parse("1 Jan 2007");
DateTime targetDate = DateTime.Parse("1 Jan 2007");
bool result;

result = startDate > endDate;		// result = false
result = startDate < endDate;		// result = true
result = startDate >= endDate;		// result = false
result = startDate <= endDate;		// result = true
result = targetDate > endDate;		// result = false
result = targetDate < endDate;		// result = false
result = targetDate >= endDate;		// result = true
result = targetDate <= endDate;		// result = true

In addition, the DateTime structure includes the comparison methods, Equals, Compare and CompareTo. These operate in much the same way as for the string class and were described in the earlier article, 'C# String Comparison Functions'.

DateTime Component Extraction

The DateTime data type provides a complex structure of numbers representing a date and time, including a year, month, day, hour, etc. The structure incorporates all of the rules of standard date and time information, automatically dealing with problems such as determining the number of days in each month and working with leap years. This information is readily obtained using the range of available properties and methods.

Extraction of Specific DateTime Components

The DateTime structure holds numeric values for the Year, Month, Day, Hour, Minute Second and Millisecond of a time. Each of these can be extracted independently as an integer using the structure's properties. The following example defines a date and time with an accuracy in milliseconds and demonstrates how the various values are accessed.

DateTime theDate = DateTime.Parse("30 Dec 2006 01:02:03.456 PM");

int year = theDate.Year;                // year = 2006
int month = theDate.Month;              // month = 12
int day = theDate.Day;                  // day = 30
int hour = theDate.Hour;                // hour = 13
int minute = theDate.Minute;            // minute = 2
int second = theDate.Second;            // second = 3
int millisecond = theDate.Millisecond;  // millisecond = 456

Note that the properties are read-only, allowing the values to be extracted but not modified. However, a new DateTime value can be generated using the extracted values. This is achieved using a constructor as described in the previous article of the C# Fundamentals tutorial.

Extraction of Date or Time

It is often necessary to extract just the date or time part from a DateTime value. The date can be obtained from the Date property, which returns a DateTime value with the time part set to midnight.

DateTime theDate = DateTime.Parse("31 Dec 2006 13:14:15");

DateTime dateOnly = theDate.Date;       // dateOnly = 31 Dec 2006 00:00:00

The TimeOfDay property returns a TimeSpan value. The TimeSpan structure is designed to hold a period of time, rather than an instant in time signified by a DateTime. It has similar properties to the DateTime structure but holds only days, hours, minutes, seconds and milliseconds. An example of a TimeSpan value is 1.12:05:01 indicating a duration of one day, twelve hours, five minutes and one second.

When using the TimeOfDay property of a DateTime, the returned TimeSpan is populated with the time element only. The Days property is set to zero.

DateTime theDate = DateTime.Parse("31 Dec 2006 13:14:15");

TimeSpan timeOnly = theDate.TimeOfDay;  // timeOnly = 0.13:14:15

DayOfWeek Property

The DayOfWeek property allows you to determine the weekday that a particular date falls upon. The property returns an enumerated type value. An enumerated type provides a list of named numbers, in this case the numbers zero to six represent the day names Sunday to Saturday. The DayOfWeek value may be converted to either a number or a string depending upon the desired use.

DateTime theDate = DateTime.Parse("31 Dec 2006");

DayOfWeek day = theDate.DayOfWeek;      // day = 0 (Sunday)
int dayNumber = (int)day;               // dayNumber = 0
string dayString = day.ToString();      // dayString = "Sunday"

DayOfYear Property

Sometimes a date must be expressed as a simple integer, being the number of days passed since the start of the current year. The DateTime structure allows this via the DayOfYear property. This property returns a day number within the current year. For 1 January the return value is one. For 31 December, the returned value is 365, or 366 for leap years.

DateTime standard = DateTime.Parse("25 March 2006");
DateTime leapyear = DateTime.Parse("25 March 2008");
int day;

day = standard.DayOfYear;               // day = 84
day = leapyear.DayOfYear;               // day = 85

Determining Calendar Information

Finally, you can use the DateTime class to obtain information about a specific month or year, which is useful when displaying or processing calendar information. The first method to review is DaysInMonth. This accepts year and month numbers as parameters and returns the number of days in that month. The second, IsLeapYear, returns a Boolean value indicating if a given year is a leap year. Both methods are static members.

int days = DateTime.DaysInMonth(2008, 2);   // days = 29
bool leap = DateTime.IsLeapYear(2008);      // leap = true
1 January 2007