Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
(ebook) Visual Studio .NET Mastering Visual Basic.pdf
Скачиваний:
120
Добавлен:
17.08.2013
Размер:
15.38 Mб
Скачать

552 Chapter 12 HANDLING STRINGS, CHARACTERS, AND DATES

When executed, this code will pop up a message box with a statement like the following:

Located 22 instances of the word in 270 milliseconds

The last few statements calculate the time it took the program to locate all the instances of the word with the methods of the TimeSpan object, which is discussed in the following section.

Handling Dates

Another common task in coding business applications is the manipulation of dates and time. To aid the coding of these tasks, the Framework provides the DateTime and TimeSpan classes. The DateTime class handles date and time values, while the TimeSpan class handles time differences. Date is a data type, and there’s no equivalent class in the Framework. All Date variables are implemented by the DateTime class. The two types of variables are identical, and the DateTime name is more appropriate, since these variables can store both dates and times. Since the Date data type has been around for a while, I will use this name for the class. But keep in mind that there’s no Date class and you must use the System.DateTime class to call the shared members of a Date variable.

VB.NET supports all the date and time functions of previous versions of Visual Basic, which are described in detail in a bonus reference on the CD.

The DateTime Class

The DateTime class is used for storing date and time values, and it’s one of the Framework’s base data types. Date and time values are stored internally as double numbers. The integer part of the value corresponds to the data and the fractional part corresponds to the time. To convert a Date variable to a double value, use the method ToOADateTime, which returns a value that is an OLE Automation–compatible date. The value 0 corresponds to the midnight of December 30, 1899.

To initialize a Date variable, supply a date value enclosed in a pair of pound symbols. If the value contains time information, separate it from the date part with a space:

Dim date1 As Date = #4/15/2001#

Dim date2 As Date = #4/15/2001 14:01:59#

You can declare the two variables as DateTime type. If you have a string that represents a date and you want to assign it to a Date variable for further processing, use the DateTime class’s Parse and ParseExact methods. The Parse method parses a string and returns a date value, if the string can be interpreted as a date value. Let’s say your code prompts the user for a date and then it uses in date calculations. The user-supplied date is read as a string, and you must convert it to a Date value:

Dim sDate1 As String

Dim dDate1 As Date

sDate1 = InputBox(“Please enter a date after 1/1/2002”) Try

dDate1 = System.DateTime.Parse(sDate1) { use dDate1 in your calculations }

Catch exc As Exception

MsgBox(“You’ve entered an invalid date”) End Try

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

HANDLING DATES 553

The Parse method will convert a string that represents a date to a DateTime value regardless of the format of the date. You can enter dates like “1/17/2001”, “Jan. 17, 2003”, or “January 17, 2003” (with or without the comma). Actually, even the string “17/1/2003” will be read as January 17, because there are only 12 months, and this is the only interpretation that will yield a valid date. VB assumes you’ve entered a European-style date and swaps the day and month values, if the month value is invalid.

Properties

The Date type exposes the following properties, which are straightforward.

Date

The Date property returns the date from a date/time value and sets the time to midnight. The statements:

Dim date1 As Date date1 = Now()

Console.WriteLine(date1)

Console.WriteLine(date1.Date)

will print something like the following values in the Output window:

5/29/2001 2:30:17 PM 5/29/2001 12:00:00 AM

DayOfWeek, DayOfYear

These two properties return the day of the week (a number from 1 to 7) and the number of the day in the year (an integer from 1 to 365, or 366 for leap years).

Hour, Minute, Second, Millisecond

These properties return the corresponding time part of the Date value passed as arguments. If the current time is 1:35:22 P.M., the three properties of the DateTime class will return the following values when applied on the current date and time:

Console.WriteLine(“The current time is “ & Date.Now.TimeOfDay.ToString) Console.WriteLine(“The hour is “ & Date.Now.Hour) Console.WriteLine(“The minute is “ & Date.Now.Minute) Console.WriteLine(“The second is “ & Date.Now.Second)

If you place these statement in a button’s Click event handler and execute them, the following will be printed on the Output window:

The current time is 13:35:22.0527552

The hour is 13

The minute is 35

The second is 22

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

554 Chapter 12 HANDLING STRINGS, CHARACTERS, AND DATES

Day, Month, Year

These three properties return the day of the month, the month, and the year of the Date value passed as argument. The Day and Month properties are numeric values, but you can convert them to the appropriate string (the name of the day or month) with the WeekDayName() and MonthName() functions. Both functions accept as argument the number of the day (a value from 1 to 7) or month (from 1 to 13), and they return the name. Use the value 13 with a 13-month calendar (for non-U.S. or non-European calendars). They also accept a second optional argument that is a True/False value and indicates whether the function should return the abbreviated name (if True) or full name (if False). The WeekDayName() function accepts a third optional argument, which determines the first day of the week. Set this argument to one of the members of the FirstDayOfWeek enumeration. By default, the first day of the week is Sunday.

Ticks

This property returns the number of ticks from a date/time value. Each tick is 100 nanoseconds (or 0.0001 milliseconds). To convert ticks to milliseconds, multiply them by 10,000 (or use the TimeSpan object’s TicksPerMillisecond property, discussed later in this chapter).

TimeOfDay

This property returns the time from a date/time value. The following statement will return a value like the one shown after the statement, in bold:

Console.WriteLine(Now().TimeOfDay)

14:35:44.4589088

Methods

The DateTime class exposes several methods for manipulating dates. The most practical methods add and subtract time intervals to and from an instance of the DateTime class.

Compare

Compare is a shared method that compares two date/time values and returns an integer value indicating the relative order of the two values. The syntax of the Compare method is

order = System.DateTime.Compare(date1, date2)

where date1 and date2 are the two values to be compared. The method returns an integer, which is –1 if date1 is less than date2, 0 if they’re equal, and 1 if date1 is greater than date2.

DaysInMonth

This shared method returns the number of days in a specific month. Because February contains a variable number of days depending on the year, the DaysInMonth method accepts as arguments both the month and the year:

monDays = System.DateTime.DaysInMonth(year, month)

To find out the number of days in February 2009, use the following expression:

FebDays = System.DateTime.DaysInMonth(2, 2009)

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

HANDLING DATES 555

FromOADate

This shared method creates a date/time value from an OLE Automation Date.

newDate = System.DateTime.FromOADate(dtvalue)

The argument dtvalue must be a Double value in the range from –657,434 (first day of year 100) to 2,958,465 (last day of year 9999).

IsLeapYear

This shared method returns a True/False value that indicates whether the specified year is leap or not.

Dim leapYear As Boolean

leapYear = System.DateTime.IsLeapYear(year)

Add

This method adds a TimeSpan object to the current instance of the Date class. The TimeSpan object represents a time interval and there are many methods to create a TimeSpan object, which are all discussed in the section “The TimeSpan Class” later in this chapter. The following statements create a new TimeSpan object that represents 3 days, 6 hours, 2 minutes, and 50 seconds, and add this TimeSpan to the current date and time. Depending on when these statements are executed, the two date/time values will differ, but the difference between them will always be 3 days, 6 hours, 2 minutes, and 50 seconds:

Dim TS As New TimeSpan()

Dim thisMoment As Date = Now()

TS = New TimeSpan(3, 6, 2, 50)

Console.WriteLine(thisMoment)

Console.WriteLine(thisMoment.Add(TS))

The values printed in the Output window when I tested this code segment were:

2001-04-13 16:26:38

2001-04-16 22:29:28

Subtract

This method is the counterpart of the Add method; it subtracts a TimeSpan object from the current instance of the Date class and returns another Date value. The following statements create a new TimeSpan object that represents 3 days, 6 hours, 2 minutes, and 50 seconds, and subtracts this TimeSpan from the current date and time. Depending on when these statements are executed, the two date/time values will differ, but the difference between them will always be the same:

Dim TS As New TimeSpan()

Dim thisMoment As Date = Now()

TS = New TimeSpan(3, 6, 2, 50)

Console.WriteLine(thisMoment)

Console.WriteLine(thisMoment.Subtract(TS))

The values printed in the Output window when I tested this code segment were:

5/29/2001 2:52:03 PM 5/26/2001 8:49:13 AM

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

556 Chapter 12 HANDLING STRINGS, CHARACTERS, AND DATES

Adding Intervals to Dates

Various methods add specific intervals to a date/time value. Each method accepts the number of intervals to add (days, hours, milliseconds, and so on). These methods are simply listed: AddYears, AddMonths, AddDays, AddHours, AddMinutes, AddSeconds, AddMilliseconds, and AddTicks. A tick is 100 nanoseconds and is used for really fine timing operations.

To add 3 years and 12 hours to the current date, use the following statements:

Dim aDate As Date aDate = Now()

aDate = aDate.AddYears(3) aDate = aDate.AddHours(12)

If the argument is a negative value, the corresponding intervals are subtracted from the current instance of the class. The following statement subtracts 2 minutes from a Date variable:

aDate = aDate.AddMinutes(-2)

ToString

This method converts a date/time value to a string, using a specific format. The Date class recognizes numerous format patterns, which are listed in the following two tables. Table 12.1 lists the standard format patterns, and Table 12.2 lists the format characters that can format individual parts of the date/time value. You can combine the custom format characters to format dates and times in any way you wish.

The syntax of the ToString method is

aDate.ToString(formatSpec)

where formatSpec is a format specification. The “D” named date format, for example, formats a date value as a long date, and the following statement will return the string shown below the statement in bold:

Console.Writeline(#9/17/2005#.ToString(“D”))

Saturday, September 17, 2005

Table 12.1 lists the named formats for the standard date and time patterns. The format characters are case-sensitive; for example, “g” and “G” represent slightly different patterns.

Table 12.1: The Date and Time Named Formats

Named Format

Output

d

MM/dd/yyyy

D

dddd, MMMM dd, yyyy

f

dddd, MMMM dd, yyyy HH:mm

F

dddd, MMMM dd, yyyy HH:mm:ss

g

MM/dd/yyyy HH:mm

Format Name

ShortDatePattern

LongDatePattern

fulldatetimePattern (long date and short time) FullDateTimePattern (long date and long time) general (short date and short time)

Continued on next page

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

 

 

HANDLING DATES

557

 

 

 

 

 

 

 

 

 

Table 12.1: The Date and Time Named Formats (continued)

 

 

 

Named Format

Output

Format Name

G

MM/dd/yyyy HH:mm:ss

General (short date and long time)

m, M

MMMM dd

MonthDayPattern

r, R

ddd, dd MMM yyyy HH‘:’mm‘:’ss ‘GMT’

RFC1123Pattern

s

yyyy-MM-dd HH:mm:ss

SortableDateTimePattern

t

HH:mm

ShortTimePattern

T

HH:mm:ss

LongTimePattern

u

yyyy-MM-dd HH:mm:ss

UniversalSortableDateTimePattern

U

dddd, MMMM dd, yyyy HH:mm:ss

UniversalSortableDateTimePattern

y, Y

MMMM, yyyy

YearMonthPattern

 

 

 

 

 

The following examples format the current date using all of the format patterns listed in Table 12.1. An example of the output produced by each statement is shown under each statement, in bold.

Console.WriteLine(now().ToString(“d”))

5/29/2001

Console.WriteLine(now().ToString(“D”))

Tuesday, May 29, 2001

Console.WriteLine(now().ToString(“f”))

Tuesday, May 29, 2001 3:14 PM

Console.WriteLine(now().ToString(“F”))

Tuesday, May 29, 2001 3:14:43 PM

Console.WriteLine(now().ToString(“g”))

5/29/2001 3:14 PM

Console.WriteLine(now().ToString(“G”))

5/29/2001 3:14:43 PM

Console.WriteLine(now().ToString(“m”))

May 29

Console.WriteLine(now().ToString(“r”))

Tue, 29 May 2001 15:14:43 GMT

Console.WriteLine(now().ToString(“s”))

2001-05-29T15:14:43

Console.WriteLine(now().ToString(“t”))

3:14 PM

Console.WriteLine(now().ToString(“T”))

3:14:43 PM

Console.WriteLine(now().ToString(“u”))

2001-05-29 15:14:43Z

Console.WriteLine(now().ToString(“U”))

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

558 Chapter 12 HANDLING STRINGS, CHARACTERS, AND DATES

Tuesday, May 29, 2001 12:14:43 PM

Console.WriteLine(now().ToString(“y”))

May, 2001

Table 12.2 lists the format characters that can be combined to build custom format date and time values. The patterns are case-sensitive; for example, “MM” is valid, but “mm” isn’t. If the custom pattern contains spaces or characters enclosed in single quotation marks, these characters will appear in the formatted string.

Table 12.2: Date Format Specifier

Format Character

Description

d

The date of the month

dd

The day of the month with a leading zero for single-digit days

ddd

The abbreviated name of the day of the week (a member of the AbbreviatedDay-

 

Names enumeration)

dddd

The full name of the day of the week (a member of the DayNamesFormat

 

enumeration)

M

The number of the month

MM

The number of the month with a leading zero for single-digit months

MMM

The abbreviated name of the month (a member of the AbbreviatedMonthNames

 

enumeration)

MMMM

The full name of the month

y

The year without the century (the year 2001 will be printed as 1)

yy

The year without the century (the year 2001 will be displayed as 01)

yyyy

The complete year

gg

The period or era (this pattern is ignored if the date to be formatted does not

 

have an associated period, such as A.D. or B.C.)

h

The hour in 12-hour format

hh

The hour in 12-hour format with a leading zero for single-digit hours

H

The hour in 24-hour format

HH

The hour in 24-hour format with a leading zero for single-digit hours

m

The minute of the hour

mm

The minute of the hour with a leading zero for single-digit minutes

s

The second of the hour

ss

The second of the hour with a leading zero for single-digit seconds

 

Continued on next page

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

HANDLING DATES 559

Table 12.2: Date Format Specifier (continued)

Format Character

Description

t

The first character in the AM/PM designator

tt

The AM/PM designator

z

The time-zone offset (applies to hours only)

zz

The time-zone offset with a leading zero for single-digit hours (applies to

 

hour only)

zzz

The full time-zone offset (hour and minutes) with leading zeros for single-digit

 

hours and minutes

 

 

The following examples format the current time using all of the format patterns listed in Table 12.2. An example of the output produced by each statement is shown under each statement, indented and in bold.

Console.WriteLine(now().ToString(“m/d/yyyy”))

5/29/2001

Console.WriteLine(now().ToString(“dd”))

29

Console.WriteLine(now().ToString(“ddd”))

Tue

Console.WriteLine(now().ToString(“dddd”))

Tuesday

Console.WriteLine(now().ToString(“M/yyyy”))

May 2001

Console.WriteLine(now().ToString(“MM”))

05

Console.WriteLine(now().ToString(“MMM”))

May

Console.WriteLine(now().ToString(“MMMM”))

May

Console.WriteLine(now().ToString(“m/d/y”))

29/5/1

Console.WriteLine(now().ToString(“m/d/yy”))

29/5/01

Console.WriteLine(now().ToString(“yy”))

01

Console.WriteLine(now().ToString(“yyyy”))

2001

Console.WriteLine(now().ToString(“gg”))

A.D.

Console.WriteLine(now().ToString(“hh”))

03

Console.WriteLine(now().ToString(“HH”))

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

560 Chapter 12 HANDLING STRINGS, CHARACTERS, AND DATES

15

Console.WriteLine(now().ToString(“h:m”))

3:26

Console.WriteLine(now().ToString(“mm”))

26

Console.WriteLine(now().ToString(“h:m:s”))

3:26:38

Console.WriteLine(now().ToString(“hh:mm:ss”))

03:26:38

Console.WriteLine(now().ToString(“h:m:s t”))

3:26:38 P

Console.WriteLine(now().ToString(“tt”))

PM

Console.WriteLine(now().ToString(“zz”))

+03

Console.WriteLine(now().ToString(“zzz”))

+03:00

To display the day of the month and the month name only, for instance, use the following statement:

Console.WriteLine(now().ToString(“MMMM d”))

May 29

You may have noticed some overlap between the named formats and the format characters. The character “d” signifies the short date pattern when used as a named format and the number of the day when used as format character. The compiler figures out how it’s used based on the context. If the format argument is “d/mm”, the program will display the day and month number, while the format argument “d, mmm” will display the number of the day followed by the month’s name. If you use the character “d” on its own, however, it will be interpreted as the named format for the short date format.

Date Conversion Methods

The Date class supports methods for converting a date/time value to many of the other base types. The most common ones are ToInt16, ToSingle, ToString, ToUInt16, ToUInt32, and ToUInt64. When a date/time value is converted an integer value, the time value is obviously lost. The other conversion methods require some explanation:

ToFileTime Converts the value of the current Date instance to the format of the local system file time. There’s also an equivalent FromFileTime method, which converts a file time value to a Date value.

ToLocalTime Converts a UTC time value to local time.

ToLongDateString, ToShortDateString These two methods convert the date part of the current Date instance to a string with the long (or short) date format. The following statement will return a value like the one shown in bold, which is the long date format:

Console.WriteLine(Now().ToLongDateString)

Friday, July 16, 2001

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

HANDLING DATES 561

The following statement will convert the current date to the short date format:

Console.WriteLine(Now().ToShortDateString)

7/16/2001

ToLongTimeString, ToShortTimeString These two methods convert the time part of the current instance of the Date class to a string with the long (or short) time format. The following statement will return a value like the one shown in bold:

Console.WriteLine(Now().ToLongTimeString)

6:40:53 PM

The following statement will convert the current time to the short date format:

Console.WriteLine(Now().ToShortTimeString)

6:40 PM

ToOADate Converts the DateTime instance into an OLE Automation–compatible date.

ToUniversalTime Converts the current instance of the DateTime class into universal coordinated time (UCT). If you convert the local time of a system in New York to UCT when daylight savings is not in effect, the value returned by this method will be a date/time value that’s five hours ahead. The date may be the same or the date of the following day. If the statement is executed after 7 P.M. local time, the date will be that of the following day.

Dates as Numeric Values

The Date type encapsulates very complicated operations. Manipulating dates is one of the most cumbersome tasks in programming, if you consider that not all months have the same number of days. For years, programmers had to write code to manipulate dates, or buy libraries with dateand time-handling functions. To get an idea of how the Framework handles dates, let’s experiment a little with them. Start by declaring two variables, a Date and a Double, and initialize the Date variable to the current date:

Dim Date1 As Date

Date1 = Now()

Dim dbl As Double

Insert a couple of statements to convert the date to a Double value and print it:

dbl = Date1.ToOADate Console.WriteLine(dbl)

On the date I tested this code, April 10, 2001, the value was 36,991.63150635417. The integer part of this value is the date, and the fractional part is the time. If you add one day to the current date and then convert it to a Double again, you’ll get a Double value:

dbl = Now().AddDays(1).ToOADate Console.WriteLine(dbl)

This time, the value 36,992.63150635417 was printed. You can add two days to the current date by adding (48 × 60) minutes. The original integer part of the numeric value will be increased by two:

dbl = Now().AddMinutes(48 * 60).ToOADate Console.WriteLine(dbl)

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com