User:Foxall/13

Ka Wiktionary

Hour 13. Performing Arithmetic, String Manipulation, and Date/Time Adjustments[wax ka badal]

Just as arithmetic is a necessary part of everyday life, it's also vital to developing Windows programs. You probably won't write an application that doesn't add, subtract, multiply, or divide some numbers. In this hour, you'll learn how to perform arithmetic in code. You'll also learn about order of operator precedence, which determines how C# evaluates complicated expressions (or equations). After you understand operator precedence, you'll learn how to compare equalities�something you'll do all the time.

graphics/newterm.gif Boolean logic is the logic C# itself uses to evaluate expressions in decision-making constructs. If you've never programmed before, Boolean logic may be a new concept to you. However, in this hour I explain what you need to know about Boolean logic to create efficient code that performs as expected. Finally, I show you how to manipulate strings and work with dates and times.

The highlights of this hour include the following:

  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch13lev1sec1.htm#ch13lev1sec1 Performing arithmetic]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch13lev1sec1.htm#ch13lev2sec6 Understanding the order of operator precedence]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch13lev1sec2.htm#ch13lev1sec2 Comparing equalities]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch13lev1sec3.htm#ch13lev1sec3 Understanding Boolean logic]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch13lev1sec4.htm#ch13lev1sec4 Manipulating strings]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch13lev1sec5.htm#ch13lev1sec5 Working with dates and times]

Performing Basic Arithmetic[wax ka badal]

To be a programmer, you have to have solid math skills; you'll be performing a lot of basic arithmetic when writing C# applications. To get the results you're looking for in any given calculation, you must

  • Know the mathematical operator that performs the desired arithmetic function.
  • Understand and correctly use order of precedence.

Using the correct mathematical operator is simple. Most are easy to commit to memory, and you can always look up the ones you're not quite sure of. I'm not going to go into great detail on any of the math functions (if you've made it this far, I'm sure you have a working grasp of math), but I will cover them all.

graphics/bookpencil.gif In [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch07.htm#ch07 Hour 7], "Working with Traditional Controls," I mentioned how the System.Diagnostics.Debug.WriteLine() method prints text to the Output window. I use this method in the examples throughout this hour. You will not be asked to create a project in this chapter, but you may want to try some of these examples in a test project. Because we are planning to use several debug statements, it will be helpful to declare the System.Diagnostics namespace in the header of your class. This permits you to use the methods of the namespace without having to qualify the entire namespace. The following is the line you need to add at the beginning of your class (put it with the other using statements created automatically by C#):
using System.Diagnostics;<br />

For more specific information on the Debug object, refer to [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch16.htm#ch16 Hour 16], "Debugging Your Code."

Performing Addition 

Simple addition is performed using the standard addition symbol, the + character. The following line prints the sum of 4, 5, and 6:

Debug.WriteLine(4 + 5 + 6);

You don't have to use a hard-coded value with arithmetic operators. You can use any of the arithmetic operators on numeric variables and constants. For example:

const int c_FirstValue = 4;
const int c_SecondValue = 5;
Debug.WriteLine(c_FirstValue + c_SecondValue);

This bit of code prints the sum of the constants c_FirstValue and c_SecondValue, which, in this case, is 9.

 Performing Subtraction and Negation 

Like the addition operator, you're most likely familiar with the subtraction operator because it's the same one you would use on a calculator or when writing an equation: the � character. The following line of code prints 2 (the total of 6�4):

Debug.WriteLine(6 - 4);

As with written math, the � character is also used to denote a negative number. For example, to print the value �6, you would use a statement such as the following:

Debug.WriteLine(-6);

Performing Multiplication

If you work with adding machines, you already know the multiplication operator. The multiplication character is the asterisk (*) character. You can enter this character using Shift+8 or by pressing the * key located in the upper row of the keypad section of the keyboard. Although you would ordinarily use an "x" when writing multiplication equations such as 6 = 3x2 on paper, you'll receive an error if you try this in code; you have to use the * character. The following statement prints 20 (5 multiplied by 4):

Debug.WriteLine(5 * 4);

Performing Division

Division is accomplished using the slash (/) operator. This operator is easy to remember if you think of division as fractions. For example, one-eighth is written as 1/8, which literally means one divided by eight. The following statement prints 8 (32 divided by 4):

Debug.WriteLine(32 / 4);

C# overloads the division operator. This means that based on the input arguments, the results may vary. For example, C# division will return an integer when dividing integers, but it will return a fractional number if a float, a double, or a decimal data type is used. Hence, 32 / 5 will return 6, dropping the remainder (2, in this case). If you wanted to return the actual value of the operation 32 / 5, you would have to specify the numbers with decimal places (that is, 32.0 / 5.0).

graphics/bulb.gif The modulus operator (%) can be used to find the remainder of an integer division.
Performing Modulus Arithmetic
graphics/newterm.gif Modulus arithmetic is the process of performing division on two numbers but keeping only the remainder. Modulus arithmetic is performed using the % operand, in contrast to using a slash (/) operator symbol. The following are examples of modulus statements and the values they would print:
Debug.WriteLine(10 % 5); // Prints 0

Debug.WriteLine(10 % 3); // Prints 1

Debug.WriteLine(12 % 4.3); // Prints 3.4

Debug.WriteLine(13.6 % 5); // Prints 3.6

The first two statements are relatively easy to understand: 5 goes into 10 twice with no remainder and 3 goes into 10 three times with a remainder of 1. C# processes the third statement as 4.3 going into 12 three times with a remainder of 3.4. In the last statement, C# performs the modulus operation as 5 going into 13.6 twice with a remainder of 3.6.

 Determining the Order of Operator Precedence
graphics/newterm.gif When several arithmetic operations occur within a single equation (called an expression), C# must resolve the expression in pieces. The order in which these pieces are evaluated is known as operator precedence. To fully understand operator precedence, you have to brush up a bit on your algebra (most of the math you perform in code is algebraic).

Consider the following expression:

Debug.WriteLine(6 * 5 + 4);

Two arithmetic operations occur in this single expression. To evaluate the expression, C# must perform both operations: multiplication and addition. Which operation does C# perform first? Does it matter? Absolutely. If C# performs the multiplication before the addition, you end up with the following:

graphics/13equ01.gif

graphics/13equ02.gif

The final result would be that of C# printing 34. Now look at the same equation with the addition performed prior to multiplication:

graphics/13equ03.gif

graphics/13equ04.gif

In this case, C# would print 54�a drastically different number from the one computed when the multiplication is performed first. To prevent these types of errors, C# consistently performs arithmetic operations in the same order�the order of operator precedence (in this case, multiplication and then addition). [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/13.htm#ch13table01 Table 13.1] lists the order of operator precedence for arithmetic and Boolean operators. (Boolean operators are discussed later in this hour.) If you're familiar with algebra, you'll note that the order of precedence used by C# is the same as that used in algebraic formulas.

Category Operators
Multiplicative * / %
Additive + -
Equality == (equal), != (not equal)
Logical AND &
Logical XOR ^
Logical OR
Conditional AND &&
Conditional OR
Conditional ?:
graphics/bookpencil.gif Notice that two equal signs are used to denote equality, not one as you might expect.
graphics/newterm.gif All comparison operators (discussed in the next section) have an equal precedence. When operators have an equal precedence, C# evaluates them from left to right. Notice that the multiplication and division operators have an equal precedence, so in an expression that has both, the operators would be evaluated from left to right. The same holds true for addition and subtraction. When expressions contain operators from more than one category (arithmetic, comparison, or logical), arithmetic operators are evaluated first, comparison operators are evaluated next, and logical operators are evaluated last.

Just as when writing an equation on paper, you can use parentheses to override the order of operator precedence. Operations placed within parentheses are always evaluated first. Consider the previous example:

Debug.WriteLine(6 * 5 + 4);

Using the order of operator precedence, C# evaluates the equation like this:

Debug.WriteLine((6 * 5) + 4);

The multiplication is performed first, and then the addition. If you wanted the addition performed prior to the multiplication, you could write the statement like this:

Debug.WriteLine(6 * (5 + 4));
graphics/bulb.gif When writing complex expressions, you absolutely must keep in mind the order of operator precedence and use parentheses to override the default operator precedence when necessary. Personally, I try to always use parentheses so that I'm sure of what is happening and my code is easier to read.
>

Comparing Equalities

Comparing values, particularly variables, is even more common than performing arithmetic (but you need to know how C# arithmetic works before you can understand the evaluation of equalities).

Comparison operators are most often used in decision-making structures, as explained in the next hour. Indeed, these operators are best understood using a simple if decision structure. In an if construct, C# considers the expression on the if statement, and if the expression equates to true, the code statement(s) are executed. For example, the following is an if operation (a silly one at that) expressed in English, not in C# code:

IF DOGS BARK, THEN SMILE.

If this were in C# code format, C# would evaluate the if condition, which in this case is dogs bark. If the condition is found to be true, the code following the expression is Performing Arithmetic, String Manipulation, and Date/Time Adjustments performed. Because dogs bark, you'd smile. Notice how these two things (dogs barking and you smiling) are relatively unrelated. This doesn't matter; the point is that if the condition evaluates to true, certain actions (statements) occur.

You'll often compare the value of one variable to that of another variable or to a specific value when making decisions. The following are some basic comparisons and how C# evaluates them:

Debug.WriteLine(6 > 3); // Evaluates to true

Debug.WriteLine(3 == 4); // Evaluates to false

Debug.WriteLine(3 >= 3); // Evaluates to true

Debug.WriteLine(5 <= 4); // Evaluates to false

Performing comparisons is pretty straightforward. If you get stuck writing a particular comparison, attempt to write it in English before creating it in code.

>

Understanding Boolean Logic

Boolean logic is a special type of arithmetic/comparison. Boolean logic is used to evaluate expressions down to either true or false. This may be a new concept to you, but don't worry; it's not difficult to understand. Boolean logic is performed using a logical operator. Consider the following sentence:

If black is a color and wood comes from trees then print "ice cream."

At first glance, it might seem that this is nonsensical. However, C# could make sense of this statement using Boolean logic. First, notice that three expressions are actually being evaluated within this single sentence. I've added parentheses in the following sentence to clarify two of the expressions. If (black is a color) and (wood comes from trees) then print "ice cream."

Boolean logic evaluates every expression to either true or false. Therefore, substituting true or false for each of these expressions yields the following:

if (true) And (true) then print "ice cream."

Now, for the sake of clarity, here is the same sentence with parentheses placed around the final expression to be evaluated:

If (True And True) then print "ice cream."

This is the point where the logical operators come into play. The And (&&) operator returns true if the expressions on each side of the And (&&) operator are true (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/13.htm#ch13table02 Table 13.2] for a complete list of logical operators). In the sentence we're considering, the expressions on both sides of the And (&&) operator are true, so the expression evaluates to true. Replacing the expression with true yields:

If True then print "ice cream."

This would result in the words "ice cream" being printed. If the expression had evaluated to false, nothing would be printed. As you'll see in the next hour, the decision constructs always fully evaluate their expressions to either true or false, and statements execute according to the results.

Operator Description
And (&&) Evaluates to true when the expressions on both sides are true.
Not (!) Evaluates to true when its expression evaluates to false; otherwise, it returns false (the true/false value of the expression is negated, or reversed).
Or ( ) Evaluates to true if an expression on either side evaluates to true.
Xor (^) Evaluates to true if one, and only one, expression on either side evaluates to true.

Each of these is discussed in the following sections.

 Using the And (&&) Operator 

The And (&&) operator is used to perform a logical conjunction. If the expressions on both sides of the And (&&) operator evaluate to true, the And (&&) operation evaluates to true. If either expression is false, the And (&&) operation evaluates to false, as illustrated in the following examples:

Debug.WriteLine(true && true); // Prints true

Debug.WriteLine(true && false); // Prints false

Debug.WriteLine(false && true); // Prints false

Debug.WriteLine(false && false); // Prints false

Debug.WriteLine((32 > 4) && (6 == 6)); // Prints true

Using the Not(!) Operator

The Not(!) operator performs a logical negation. That is, it returns the opposite of the expression. Consider the following examples:

Debug.WriteLine(! (true)); // Prints false

Debug.WriteLine(! (false)); // Prints true

Debug.WriteLine(! (5 == 5)); // Prints false

Debug.WriteLine(!(4 < 2)); // Prints true

The first two statements are easy enough; the opposite of true is false and vice versa. For the third statement, remember that C#'s operator precedence dictates that arithmetic operators are evaluated first (even if no parentheses are used), so the first step of the evaluation would look like this:

Debug.WriteLine( ! (true));

The opposite of true is false, of course, so C# prints false.

The fourth statement would evaluate to:

Debug.WriteLine( !(false));

This happens because 4 is not less than 2, which is the expression C# evaluates first. Because the opposite of false is true, this statement would print true.

 Using the Or (||) Operator 

The Or(||) operator is used to perform a logical disjunction. If the expression to the left or right of the Or(||) operator evaluates to true, the Or(||) operation evaluates to true. The following are examples using Or(||) operations, and their results:

Debug.WriteLine(true || true); // Prints true

Debug.WriteLine(true || false); // Prints true

Debug.WriteLine(false || true); // Prints true

Debug.WriteLine(false || false); // Prints false

Debug.WriteLine((32 < 4) || (6 == 6)); // Prints true

Using the Xor (^) Operator

The Xor(^) operator performs a nifty little function. I personally haven't had to use it much, but it's great for those times when its functionality is required. If one�and only one�of the expressions on either side of the Xor(^) operator is true, the Xor(^) operation evaluates to true. Take a close look at the following statement examples to see how this works:

Debug.WriteLine(true ^ true); // Prints false

Debug.WriteLine(true ^ false); // Prints true

Debug.WriteLine(false ^ true); // Prints true

Debug.WriteLine(false ^ false); // Prints false

Debug.WriteLine((32 < 4) ^ (6 == 6)); // Prints true
>

Manipulating Strings

Recall from the previous hour that a string is text. Although string manipulation isn't technically arithmetic, the things that you do with strings are very similar to things you do with numbers, such as adding two strings together; string manipulation is much like creating equations. Chances are you'll be working with strings a lot in your applications. C# includes a number of methods that enable you to do things with strings, such as retrieve a portion of a string or find one string within another. In the following sections, you'll learn the basics of string manipulation.

 Concatenating Strings of Text
graphics/newterm.gif C# makes it possible to "add" two strings of text together to form one string. Although purists will say it's not truly a form of arithmetic, it's very much like performing arithmetic on strings, so this hour was the logical place in which to present this material. The process of adding two strings together is called concatenation. Concatenation is very common. For example, you may want to concatenate variables with hard-coded strings to display meaningful messages to the user, such as Are you sure you wish to delete the user XXX?, where XXX is the contents of a variable.

To concatenate two strings, you use the + operator as shown in this line of code:

Debug.WriteLine("This is" + "a test.");

This statement would print:

This isa test.

Notice that there is no space between the words is and a. You could easily add a space by including one after the word is in the first string or before the a in the second string, or you could concatenate the space as a separate string, like this:

Debug.WriteLine("This is" + " " + "a test.");
graphics/newterm.gif Text placed directly within quotes is called a literal. Variables are concatenated in the same way as literals and can even be concatenated with literals. The following code creates two variables, sets the value of the first variable to "Allan," and sets the value of the second variable to the result of concatenating the variable with a space and the literal "Reed":
string strFullName;
string strFirstName = "Allan";

strFullName = strFirstName + " " + "Reed";

The final result is that the variable strFullName contains the string Allan Reed. Get comfortable concatenating strings of text�you'll do this often.

graphics/bookpencil.gif In C#, strings are immutable. What this means is that they never change. When you concatenate two strings together, neither is modified; instead a new string is created. Eventually, the garbage collector (discussed in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch24.htm#ch24 Hour 24], "The 10,000-Foot View") will clean up the unused strings. However, if you're going to be concatenating a lot of strings, this could have an adverse effect on system resources (until the garbage collector springs into action). C# includes a highly efficient way to concatenate strings via System.Text. StringBuilder. Although I can't go into the details here, I highly encourage you to research this if you plan to concatenate a lot of strings at once.
Using the Basic String Methods and Properties 

The .NET Framework includes a number of functions that make working with strings of text considerably easier than it might be otherwise. These functions let you easily retrieve a piece of text from a string, compute the number of characters in a string, and even determine whether one string contains another. The following sections summarize the basic string functions.

 Determining the Number of Characters Using Length 

The Length property of the string object returns the variable's length. The following statement prints 26, the total number of characters in the literal string "Pink Floyd reigns supreme." Remember, the quotes that surround the string tell C# that the text within them is a literal; they are not part of the string.

Debug.WriteLine(("Pink Floyd reigns supreme.").Length); // Prints 26

Retrieving Text from a String Using the Substring() Method

The Substring() method retrieves a part of a string.

The Substring() method can be used with the following parameters:

public string Substring(startposition,numberofcharacters);

For example, the following statement prints Queen, the first five characters of the string.

Debug.WriteLine(("Queen to Queen's Level Three.").Substring(0,5));

The arguments used in this Substring example are 0 and 5. The 0 indicates starting at the 0 position of the string (beginning). The 5 indicates the specified length to return (characters to retrieve).

The Substring() method is commonly used with the IndexOf() method (discussed shortly) to retrieve the path portion of a variable containing a filename and path combination, such as c:\Myfile.txt. If you know where the \character is, you can use Substring() to get the path.

graphics/bookpencil.gif If the number of characters requested is greater than the number of characters in the string, an exception (error) occurs. If you're unsure about the number of characters in the string, use the Length property of the string to find out. (Exception handling is reviewed in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch16.htm#ch16 Hour 16], "Debugging Your Code.")
Determining Whether One String Contains Another Using IndexOf() Method 

At times you'll need to determine whether one string exists within another. For example, suppose you let users enter their full name into a text box, and that you want to separate the first and last names before saving them into individual fields in a database. The easiest way to do this is to look for the space in the string that separates the first name from the last. You could use a loop to examine each character in the string until you find the space, but C# includes a string method that does this for you, faster and easier than you could do it yourself: the IndexOf() method. The basic IndexOf() method has the following syntax:

MyString.IndexOf(searchstring);

The IndexOf() method of a string searches the string for the occurrence of a string passed as an argument. If the string is found, the location of character at the start of the string is returned. If the search string is not found within the other string, -1 is returned. The IndexOf() method can be used with the following arguments:

  • public int IndexOf(searchstring);
  • public int IndexOf(searchstring, startinglocation);
  • public int IndexOf(searchstring, startinglocation, numberofcharacterstosearch);

The following code searches a variable containing the text "Jayson Goss", locates the space, and uses the Substring() method and Length property to place the first and last names in separate variables.

string strFullName = "Jayson Goss";
string strFirstName, strLastName;
int intLocation, intLength;

intLength = strFullName.Length;
intLocation = strFullName.IndexOf(" ");

strFirstName = strFullName.Substring(0,intLocation );
strLastName = strFullName.Substring(intLocation + 1);
graphics/bulb.gif This code assumes that a space will be found and that it won't be the first or last character in the string. In your applications, your code may need to be more robust, including checking to ensure that IndexOf() returned a value other than -1, which would indicate that no space was found.

When this code runs, IndexOf() returns 6, the location in which the first space is found. Notice how I subtracted an additional character when using SubString() to initialize the strLastName variable; this was to take the space into account.

 Trimming Beginning and Trailing Spaces from a String 

As you work with strings, you'll often encounter situations in which spaces exist at the beginning or ending of strings. The .NET Framework includes the following four methods for automatically removing spaces from the beginning or end of a string:

Method Description
String.Trim Removes white spaces from the beginning and end of a string.
String.TrimEnd Removes characters specified in an array of characters from the end of a string.
String.TrimStart Removes characters specified in an array of characters from the beginning of a string.
String.Remove Removes a specified number of characters from a specified index position in a string.

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 [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/13.htm#ch13table03 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.

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.

>

Summary

Being able to work with all sorts of data is crucial to your success as a C# developer. Just as you need to understand basic math to function in society, you need to be able to perform basic math in code to write even the simplest of applications. Knowing the arithmetic operators and understanding the order of operator precedence will take you a long way in performing math using C# code.

Boolean logic is a special form of evaluation used by C# to evaluate simple and complex expressions alike down to a value of true or false. In the following hours, you'll learn how to create loops and how to perform decisions in code. What you learned here about Boolean logic is critical to your success with loops and decision structures; you'll use Boolean logic perhaps even more often than you'll perform arithmetic.

Manipulating strings and dates each takes special considerations. In this hour, you learned how to work with both types of data to extract portions of values and to add pieces of data together to form a new whole. String manipulation is pretty straightforward, and you'll get the hang of it soon enough as you start to use some of the string functions. Date manipulation, on the other hand, can be a bit tricky. Even experienced developers need to refer to the online help at times. You learned the basics in this hour, but don't be afraid to experiment on your own.

Q&A
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/13.htm#qad1e44138 Q1:] Should I always specify parentheses to ensure that operators are evaluated as I expect them to be?
A1: C# never fails to evaluate expressions according to the order of operator precedence, so using parentheses isn't necessary when the order of precedence is correct for an expression. However, using parentheses assures you that the expression is being evaluated and may make the expression easier to read by other people. This really is your choice.
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/13.htm#qad1e44148 Q2:] I would like to learn more about the properties and methods available in the DateTime structure; where can I find all the members listed?
A2: I would look at the DateTime members documentation found within the .NET Framework documentation. This is available on the MSDN and as an installable option when installing Visual Studio .NET.
>

Workshop

The Workshop is designed to help you anticipate possible questions, review what you've learned, and get you thinking about how to put your knowledge into practice. The answers to the quiz are in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01.htm#app01 Appendix A],"Answers to Quizzes/Exercises."

 Quiz
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec13.htm#ch13ans01 1:] To get only the remainder of a division operation, you use which operator?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec13.htm#ch13ans02 2:] Which operation is performed first in the following expression�the addition or the multiplication?

graphics/13equ05.gif


[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec13.htm#ch13ans03 3:] Does this expression evaluate to true or to false?
((true || true) && false) == !true<br />
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec13.htm#ch13ans04 4:] Which Boolean operator performs a logical negation?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec13.htm#ch13ans05 5:] The process of appending one string to another is called?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec13.htm#ch13ans06 6:] What property can be used to return the month of a given date?
Exercises
  1. Create a project that has a single text box on a form. Assume the user enters a first name, a middle initial, and a last name into the text box. Parse the contents into three variables�one for each part of the name.
  2. Create a project that has a single text box on a form. Assume the user enters a valid birthday into the text box. Use the date functions as necessary to tell the user the number of the month in which they were born.