July 13, 2011, 8:35 a.m.
posted by seele
Working with Dates and Times
Dates are a unique beast. In some ways, they act like strings, where you can concatenate and parse pieces. In other ways, dates seem more like numbers in that you can add to or subtract from them. You'll often perform math-type functions on dates (such as adding a number of days to a date or determining the number of months between two dates), but you won't use the typical arithmetic operations. Instead, you use functions specifically designed for working with dates.
Understanding the DateTime Data Type
Working with dates is very common. No matter the application, you'll probably need to create a variable to hold a date using the DateTime data type. You can get a date into a DateTime variable in several ways. Recall that when setting a string variable to a literal value, the literal is enclosed in quotes. When setting a numeric variable to a literal number, the number is not closed in quotes:
string strMyString = "This is a string literal"; int intMyInteger = 69;
The more common way to set a DateTime variable to a literal date is to instantiate the variable passing in the date, like this (year, month, day):
DateTime dteMyBirthday = new DateTime(1969,7,22);
You cannot pass a string directly to a DateTime variable. For instance, if you let the user enter a date into a text box and you want to move the entry to a DateTime variable, you'll have to parse out the string to be able to adhere to one of the allowable DateTime constructors. The DateTime data type is one of the more complicated data types. This chapter will expose you to enough information to get started, but this is only the tip of the iceberg. I suggest reviewing the Microsoft Developers Network (MSDN) documentation of this curious data type for more information.
It's important to note that DateTime variables store a date and a timealways. Take a look at the example in the following code:
DateTime dteMyBirthday = new DateTime(1969,7,22); Debug.WriteLine(dteMyBirthday.ToString());
It produces this output:
7/22/1969 12:00:00 AM
Notice that this example printed the time 12:00:00 AM, even though no time was specified for the variable. This is the default time placed in a DateTime variable when only a date is specified. Although a DateTime variable always holds a date and a time, on occasion, you'll be concerned only with either the date or the time. Later, I'll show you how to use the GeTDateTimeFormats() method to retrieve just a date or a time.
Adding to or Subtracting from a Date or Time
To add a specific amount of time (such as one day or three months) to a specific date or time, you use methods of the DateTime class. Figure lists the methods as described in MSDN. These methods do not change the value of the current DataTime variable; instead, they return a new DateTime instance whose value is the result of the operation.
DateTime dteMyBirthday = new DateTime(1969,7,22); DateTime dteNewDate = dteMyBirthday.AddMonths(6);
After this second statement executes, dteNewDate contains the date 1/22/1970 12:00:00 AM.
The following code shows sample addition methods and the date they would return:
dteNewDate = dteMyBirthday.AddYears(2); // Returns 7/22/1971 12:00:00 AM dteNewDate = dteMyBirthday.AddMonths(5); // Returns 12/22/1969 12:00:00 AM dteNewDate = dteMyBirthday.AddMonths(-1); // Returns 6/22/1971 12:00:00 AM dteNewDate = dteMyBirthday.AddHours(7); // Returns 7/22/1969 7:00:00 AM
Retrieving Parts of a Date
Sometimes, it can be extremely useful to know just a part of a date. For example, you may have let a user enter his or her birth date, and you want to perform an action based on the month in which they were born. To retrieve part of a date, the DateTime class exposes properties such as Month, Day, Year, Hour, Minute, Second, and so on.
The following should illustrate the retrieval of some properties of the DateTime class (the instance date is 7/22/1969):
dteMyBirthday.Month // Returns 7 dteMyBirthday.Day // Returns 22 dteMyBirthday.DayOfWeek // Returns Tuesday
By the Way
The Hour property will return the hour in military format. Also, note that DayOfWeek() returns an enumerated value.
Formatting Dates and Times
As I stated earlier, at times you'll want to work with only the date or a time within a DateTime variable. In addition, you'll probably want to control the format in which a date or time is displayed. All this and more can be accomplished via the DateTime class by way of the following:
It's impossible to show everything regarding formatting a DateTime value here, but it is important to see how to use formatting to output either the date portion or the time portion of a DateTime variable.
The following illustrates some basic formatting methods available with the DateTime class. (Note that the instance date is still 7/22/1969 12:00:00 AM.)
dteMyBirthday.ToLongDateString(); // Returns Tuesday, July 22, 1969 dteMyBirthday.ToShortDateString(); // Returns 7/22/1969 dteMyBirthday.ToLongTimeString(); // Returns 12:00:00 AM dteMyBirthday.ToShortTimeString(); // Returns 12:00 AM
Retrieving the Current System Date and Time
Visual C# gives you the capability to retrieve the current system date and time. Again, this is accomplished by way of the DateTime class. For example, the Today property returns the current system date. To place the current system date into a new DateTime variable, for example, you could use a statement such as this:
DateTime dteToday = DateTime.Today;
To retrieve the current system date and time, use the Now property of DateTime, like this:
DateTime dteToday = DateTime.Now;
Commit DateTime.Today and DateTime.Now to memory. You'll need to retrieve the system date and/or time in an application, and this is by far the easiest way to get that information.