Working with Dates and Times
One of C#’s more confusing data types is DateTime. A DateTime represents a date, a time, or
both. For example, a
DateTime variable might represent Thursday April 1, 2010 at 9:15 AM.
In this lesson, you learn how to work with dates and times. You learn how to create
DateTime
variables, find the current date and time, and calculate elapsed time.
CREATING DATETIME VARIABLES
C# doesn’t have DateTime literal values so you cannot simply set a DateTime variable equal
to a value as you can with some other data types. Instead you can use the
new keyword to
initialize a new
DateTime variable, supplying arguments to define the date and time.
For example, the following code creates a
DateTime variable named aprilFools and initializes
it to the date April 1, 2010. It then displays the date using the short date format described in
Lesson 14 and by calling the variable’s
ToShortDateString method.
DateTime aprilFools = new DateTime(2010, 4, 1);
MessageBox.Show(aprilFools.ToString(“d”));
MessageBox.Show(aprilFools.ToShortDateString());
The preceding code uses a year, month, and day to initialize its DateTime variable, but the
DateTime type lets you use many different kinds of values. The three most useful combinations
of arguments specify (all as integers):
Year, month, day
Year, month, day, hour, minute, second
Year, month, day, hour, minute, second, milliseconds
You can also add a kind parameter to the end of the second and third of these combinations
to indicate whether the value represents local time or UTC time. (Local and UTC times are
15
596906c15.indd 187 4/7/10 12:32:58 PM
188
LESSON 15 Working With Dates anD times
explained in the next section.) For example, the following code creates a DateTime representing
12 noon on March 15, 2010 in the local time zone:
DateTime idesOfMarch =
new DateTime(2010, 3, 15, 12, 0, 0, DateTimeKind.Local);
LOCAL AND UTC TIME
Windows has several different notions of dates and times. Two of the most important of these are
local time and Coordinated Universal Time (UTC).
Local time is the time on your computer as it is configured for a particular locale. It’s what you and
a program’s user typically think of as time.
UTC time is basically the same as Greenwich Mean Time (GMT), the time at the Royal Academy in
Greenwich, London.
For most everyday tasks, local time is fine. If you need to compare data on computers running in
different time zones, however, UTC time can make coordination easier. For example, if you want to
know whether a customer in New York created an order before another customer created an order
in San Salvador, UTC lets you compare the times without worrying about the customers’ time zones.
A
DateTime object has a Kind property that indicates whether the object represents local time,
UTC time, or an unspecified time. When you create a
DateTime, you can indicate whether you are
creating a local or UTC time. If you do not specify the kind of time, C# assumes you are making an
unspecified time.
After you create a
DateTime, the type provides a couple of methods for converting it between local
and UTC values. The
ToLocalTime method converts a DateTime object to local time. Conversely,
the
ToUniversalTime method converts a time to UTC time.
The ToLocalTime and ToUniversalTime methods don’t affect a DateTime
if it is already in the desired format. For example, if you call
ToLocalTime
on a variable that already uses local time, the result is the same as the
original variable.
DATETIME PROPERTIES AND METHODS
The DateTime type provides many useful properties and methods for manipulating dates and
times. The following table summarizes some of
DateTimes most useful methods. Table 15-1
indicates which methods are static, meaning you invoke them using the type name rather than
a variable name, as in
DateTime.IsLeapYear(2010).
596906c15.indd 188 4/7/10 12:32:58 PM
DateTime Properties and Methods
189
TABLE 151
METHOD PURPOSE
Add
Adds a TimeSpan to the DateTime. The following section describes
TimeSpan.
AddDays
Adds a specified number of days to the DateTime.
AddHours
Adds a specified number of hours to the DateTime.
AddMinutes
Adds a specified number of minutes to the DateTime.
AddMonths
Adds a specified number of months to the DateTime.
AddSeconds
Adds a specified number of seconds to the DateTime.
AddYears
Adds a specified number of years to the DateTime.
IsDaylightSavingsTime
Returns true if the date and time is within the Daylight Savings
Time period for the local time zone.
IsLeapYear
(static) Returns true if the indicated year is a leap year.
Parse
(static) Parses a string and returns the corresponding DateTime.
Subtract
Subtracts another DateTime from this one and returns a TimeSpan.
The following section says more about
TimeSpan.
ToLocalTime
Converts the DateTime to a local value.
ToLongDateString
Returns the DateTime in long date format.
ToLongTimeString
Returns the DateTime in long time format.
ToShortDateString
Returns the DateTime in short date format.
ToShortTimeString
Returns the DateTime in short time format.
ToString
Returns the DateTime in general format.
ToUniversalTime
Converts the DateTime to a UTC value.
Table 15-2 summarizes the DateTimes most useful properties.
TABLE 152
PROPERTY PURPOSE
Date
Gets the DateTime’s date without the time.
Day
Gets the DateTime’s day of the month between 1 and 31.
DayOfWeek
Gets the DateTime’s day of the week as in Monday.
continues
596906c15.indd 189 4/7/10 12:32:59 PM
190
LESSON 15 Working With Dates anD times
PROPERTY PURPOSE
DayOfYear
Gets the DateTime’s day of the year between 1 and 366 (leap years
have 366 days).
Hour
Gets the DateTime’s hour between 0 and 23.
Kind
Returns the DateTime’s kind: Local, Utc, or Unspecified.
Millisecond
Gets the DateTime’s time’s millisecond.
Minute
Gets the DateTime’s minute between 0 and 59.
Month
Gets the DateTime’s month between 1 and 12.
Now
(static) Gets the current date and time.
Second
Gets the DateTime’s second between 0 and 59.
TimeOfDay
Gets the DateTime’s time without the date.
Today
(static) Gets the current date without a time.
UtcNow
(static) Gets the current UTC date and time.
Year
Gets the DateTime’s year.
TIMESPANS
A DateTime represents a point in time (July 20, 1969 at 20:17:40). A TimeSpan represents an
elapsed period of time (1 day, 17 hours, 27 minutes, and 12 seconds).
One of the more useful ways to make a
TimeSpan is to subtract one DateTime from another to find
the amount of time between them. For example, the following code calculates the time that elapsed
between the first and last manned moon landings:
DateTime firstLanding = new DateTime(1969, 7, 20, 20, 17, 40);
DateTime lastLanding = new DateTime(1972, 12, 11, 19, 54, 57);
TimeSpan elapsed = lastLanding - firstLanding;
Console.WriteLine(elapsed.ToString());
The code creates DateTime values to represent the times of the two landings. It then subtracts
the first date from the second to get the elapsed time and uses the resulting
TimeSpan’s ToString
method to display the duration. The following text shows the code’s output in the format
days.hours:minutes:seconds:
1239.23:37:17
TABLE 152
(continued)
596906c15.indd 190 4/7/10 12:32:59 PM
Try It
191
Table 15-3 summarizes the TimeSpans most useful properties and methods.
TABLE 153
PROPERTY MEANING
Days
The number of days.
Hours
The number of hours.
Milliseconds
The number of milliseconds.
Minutes
The number of minutes.
Seconds
The number of seconds.
ToString
Converts the TimeSpan into a string in the format
days.hours:minutes:seconds.fractionalSeconds.
TotalDays
The entire TimeSpan represented as days. For a 36-hour duration,
this would be 1.5.
TotalHours
The entire TimeSpan represented as hours. For a 45-minute
duration, this would be 0.75.
TotalMilliseconds
The entire TimeSpan represented as milliseconds. For a 1-second
duration, this would be 1,000.
TotalMinutes
The entire TimeSpan represented as minutes. For a 1-hour duration,
this would be 60.
TotalSeconds
The entire TimeSpan represented as seconds. For a 1-minute
TimeSpan, this would be 60.
Note that you can use the + and – operators to add and subtract TimeSpans, getting a new TimeSpan
as a result. This works in a fairly obvious way. For example, a 90-minute
TimeSpan minus a 30-minute
TimeSpan gives a 60-minute TimeSpan.
TRY IT
In this Try It, you use the DateTime and
TimeSpan variables to build the stopwatch
application shown in Figure 15-1. When
the user clicks the Start
Button, the pro-
gram starts its counter. When the user
clicks the Stop
Button, the program stops
the counter.
FIGURE 151
596906c15.indd 191 4/7/10 12:32:59 PM
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.23.103.112