Lesson 15

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, 2020 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 can't 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, 2020. 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(2020, 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 ...

Get C# 24-Hour Trainer, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.