Working with Dates and Times

   

Dates are a unique beast . In some ways, they act like strings, in which you can concatenate and parse pieces. In other ways, dates seem more like numbers in that you can add to or subtract from them. Although 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), you don'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 (suppose, for example, that you want your program to determine when a service contract expires ). 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 objMyBirthday = 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 MSDN documentation of this curious data type for more information.

It's important to note that DateTime variables store a date and a time ”always. For example, the following code:

 DateTime objMyBirthday = new DateTime(1969,7,22); Debug.WriteLine(objMyBirthday.ToString()); 

Produces this output:

 7/22/1969 12:00:00 AM 

Although a DateTime variable always holds a date and a time, on occasion, you'll only be concerned with either the date or the time. Notice that the previous 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. 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 (see Table 13.3). 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.

Table 13.3. Available Data Adding Methods (Source MSDN)
Method Description
Add Adds the value of the specified TimeSpan instance to the value of this instance.
AddDays Adds the specified number of days to the value of this instance.
AddHours Adds the specified number of hours to the value of this instance.
AddMilliseconds Adds the specified number of milliseconds to the value of this instance.
AddMinutes Adds the specified number of minutes to the value of this instance.
AddMonths Adds the specified number of months to the value of this instance.
AddSeconds Adds the specified number of seconds to the value of this instance.
AddYears Adds the specified number of years to the value of this instance.

For instance, to add six months to the date 7/22/69, you could use the following statements:

 DateTime objMyBirthday = new DateTime(1969,7,22); DateTime objNewDate = objMyBirthday.AddMonths(6); 

After this second statement executes, objNewDate contains the date 1/22/1970 12:00:00 AM .

The following code shows sample addition methods and the date they would return:

 objNewDate = objMyBirthday.AddYears(2);    // Returns 7/22/1971   12:00:00 AM objNewDate = objMyBirthday.AddMonths(5);   // Returns 12/22/1971   12:00:00 AM objNewDate = objMyBirthday.AddMonths(-1);  // Returns 6/22/1971   12:00:00 AM objNewDate = objMyBirthday.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 still 7/21/1969):

 objMyBirthday.Month         // Returns 7 objMyBirthday.Day           // Returns 22 objMyBirthday.DayOfWeek     // Returns DayOfWeek.Monday 
graphics/bookpencil.gif

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:

  • Using the DateTime methods to retrieve formatted strings

  • Using standard-format strings

  • Using custom-format strings

I can't possibly show you everything regarding formatting a DateTime value here, but I do want to show you how to use formatting to output either the date portion or the time portion of a DateTime variable. (The DateTime class is comprehensive; you'll most likely want to investigate it more thoroughly as you continue in your programming efforts.)

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)

 objMyBirthday.ToLongDateString();     // Returns Monday, July 21, 1969 objMyBirthday.ToShortDateString();    // Returns 7/21/1969 objMyBirthday.ToLongTimeString();     // Returns 12:00:00 AM objMyBirthday.ToShortTimeString();    // Returns 12:00 AM 

Retrieving the Current System Date and Time

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 objToday =  DateTime.Today; 

To retrieve the current system date and time, use the Now property of DateTime, like this:

 DateTime objToday =  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.


   
Top


Sams Teach Yourself C# in 24 Hours
Sams Teach Yourself Visual Basic 2010 in 24 Hours Complete Starter Kit (Sams Teach Yourself -- Hours)
ISBN: 0672331136
EAN: 2147483647
Year: 2002
Pages: 253
Authors: James Foxall

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net