Tải bản đầy đủ - 0 (trang)
2-8. Add, Subtract, and Compare Dates and Times

# 2-8. Add, Subtract, and Compare Dates and Times

Tải bản đầy đủ - 0trang

CHAPTER 2 ■ DATA MANIPULATION

Solution

Use the DateTime and TimeSpan structures, which support standard arithmetic and comparison

operators.

How It Works

A DateTime instance represents a specific time (such as 4:15 a.m. on September 5, 1970), whereas a

TimeSpan instance represents a period of time (such as 2 hours, 35 minutes). You may want to add,

subtract, and compare TimeSpan and DateTime instances.

Internally, both DateTime and TimeSpan use ticks to represent time. A tick is equal to 100

nanoseconds (ns). TimeSpan stores its time interval as the number of ticks equal to that interval, and

DateTime stores time as the number of ticks since 12:00:00 midnight on January 1 in 0001 CE. (CE stands

for Common Era and is equivalent to AD in the Gregorian calendar.) This approach and the use of

operator overloading makes it easy for DateTime and TimeSpan to support basic arithmetic and

comparison operations. Table 2-4 summarizes the operator support provided by the DateTime and

TimeSpan structures.

Table 2-4. Operators Supported by DateTime and TimeSpan

Operator

TimeSpan

DateTime

Assignment (=)

Because TimeSpan is a structure,

assignment returns a copy, not a

reference

Because DateTime is a structure,

assignment returns a copy, not a

reference

Adds a TimeSpan instance to a DateTime

instance

Subtraction (-)

Subtracts one TimeSpan instance from

another TimeSpan instance

Subtracts a TimeSpan instance or a

DateTime instance from a DateTime

instance

Equality (==)

Compares two TimeSpan instances and

returns true if they are equal

Compares two DateTime instances and

returns true if they are equal

Inequality (!=)

Compares two TimeSpan instances and

returns true if they are not equal

Compares two DateTime instances and

returns true if they are not equal

Greater than (>)

Determines if one TimeSpan instance is

greater than another TimeSpan instance

Determines if one DateTime instance is

greater than another DateTime instance

Greater than or

equal to (>=)

Determines if one TimeSpan instance is

greater than or equal to another

TimeSpan instance

Determines if one DateTime instance is

greater than or equal to another

DateTime instance

75

www.it-ebooks.info

CHAPTER 2 ■ DATA MANIPULATION

Operator

TimeSpan

DateTime

Less than (<)

Determines if one TimeSpan instance is

less than another TimeSpan instance

Determines if one DateTime instance is

less than another DateTime instance

Less than or

equal to (<=)

Determines if one TimeSpan instance is

less than or equal to another TimeSpan

Determines if one DateTime instance is

less than or equal to another DateTime

instance

Unary negation

(-)

Returns a TimeSpan instance with a

negated value of the specified TimeSpan

instance

Not supported

Unary plus (+)

Returns the TimeSpan instance specified

Not supported

subtract using negative values) the appropriate element of time to a DateTime instance. These methods

and the operators listed in Table 2-4 do not modify the original DateTime; instead, they create a new

instance with the modified value.

The Code

The following example demonstrates the use of operators to manipulate the DateTime and TimeSpan

structures:

using System;

namespace Apress.VisualCSharpRecipes.Chapter02

{

class Recipe02_08

{

public static void Main()

{

// Create a TimeSpan representing 2.5 days.

TimeSpan timespan1 = new TimeSpan(2, 12, 0, 0);

// Create a TimeSpan representing 4.5 days.

TimeSpan timespan2 = new TimeSpan(4, 12, 0, 0);

// Create a TimeSpan representing 3.2 days.

// using the static convenience method

TimeSpan timespan3 = TimeSpan.FromDays(3.2);

// Create a TimeSpan representing 1 week.

TimeSpan oneWeek = timespan1 + timespan2;

76

www.it-ebooks.info

CHAPTER 2 ■ DATA MANIPULATION

// Create a DateTime with the current date and time.

DateTime now = DateTime.Now;

// Create a DateTime representing 1 week ago.

DateTime past = now - oneWeek;

// Create a DateTime representing 1 week in the future.

DateTime future = now + oneWeek;

// Display the DateTime instances.

Console.WriteLine("Now

: {0}", now);

Console.WriteLine("Past : {0}", past);

Console.WriteLine("Future: {0}", future);

// Use the comparison operators.

Console.WriteLine("Now is greater than past: {0}", now > past);

Console.WriteLine("Now is equal to future: {0}", now == future);

// Wait to continue.

Console.WriteLine("\nMain method complete. Press Enter");

}

}

}

2-9. Sort an Array or a Collection

Problem

You need to sort the elements contained in an array or a collection.

Solution

Use the static System.Linq.Enumerable.OrderBy method to sort generic collections and arrays. For other

collections, use the Cast method to convert to a generic collection and then use Enumerable.OrderBy. Use

ArrayList.Sort for ArrayList objects.

How It Works

The static Enumerable.OrderBy method takes an implementation of the IEnumerable interface and a

function delegate (which can be a lambda expression). The generic collection classes all implement

IEnumerable and they, as well as arrays, can be sorted. The function delegate allows you to specify

which property or method will be used to sort the data—the parameter is a data element from the

collection or array and the return value is what you wish to represent that value in the sort operation.

So, for example, if you wish to sort a collection of MyType instances using the myProperty property for

sorting, you would call

77

www.it-ebooks.info

CHAPTER 2 ■ DATA MANIPULATION

List list = new List();

Enumerable.OrderBy(list, x => x.myProperty);

Enumerable.OrderBy returns an instance of IOrderedEnumerable, which you can use to enumerate the

sorted data (for example, in a foreach loop) or use to create a new sorted collection, by calling the

ToArray, ToDictionary, or ToList method.

Nongeneric collections (those that are created without the syntax) must be converted to

generic collections using the Cast<> method. You must either ensure that all of the items in your

collection are of the type specified or use Cast