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
DateTime’s 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