
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 ...