Visual C# 2005 Guide
The DateTime Structure

There are lots of situations where it necessary for programmers to wok with dates or times. The DateTime structure contains many properties and methods to make this easier.

When you declare a variable of the type DateTime, it represents an instant in time, normally expressed as a date and time of day.

For example,

DateTime now = DateTime.Today;
Console.WriteLine("Today's date is {0} ",now);
DateTime currTimeAndDate = DateTime.Now;
Console.WriteLine("The curent date and time is {0}", currTimeAndDate);
DateTime tomorrow = currTimeAndDate.AddDays(1);
Console.WriteLine("Tomorrow it will be {0} ", tomorrow);
DateTime then = new DateTime(2000,1,1);
Console.WriteLine("The first day of 2000 was {0}", then.DayOfWeek);

Type in and run the program above. Adapt the program to tell you what the day of the week was when you were born.

Creating A New DateTime

The constructor function for the DateTime structure is overloaded. This means that there are multiple ways to create DateTimes. You are most likely to use the following,

DateTime myDate = New DateTime(year, month, day);
DateTime myDateTime = New DateTime(year, month, day, hour, minute, second);

DateTime Properties

The following properties are used to create and manipulate instances of DateTime structure.

DateGets the date component DateTime
DayGets the day component Integer
DayOfWeekGets the week dayDayOfWeek Enumeration
HourGets the hour componentInteger
MillisecondGets the millisecond componentInteger
MinuteGets the minute componentInteger
MonthGets the month componentInteger
NowGets a DateTime object that is the current date and timeDateTime
SecondGets the second componentInteger
TimeOfDayGets the time part of a DateTime instanceTimeSpan
TodayGets a DateTime object that is the current date and time set to 00:00:00DateTime
YearGets the year componentInteger

DateTime Methods

The following methods can be used to manipulate a DateTime instance. Look at how some of these are used in the example above.

AddDays(d)Adds d days to the DateTime
AddHours(h)Adds h hours to the DateTime
AddMilliseconds(m)Adds m milliseconds to the DateTime
AddMinutes(m)Adds m minutes to the DateTime
AddMonths(m)Adds m months to the DateTime
AddSeconds(s)Adds s seconds to the DateTime
AddYears(y)Adds y years to the DateTime
DaysInMonth(y, m)Returns an integer equal to the number of days in month m of year y.
IsLeapYear(y)Returns a Boolean (true or false)
ToShortDateString()Returns a short string representation of the date component of a DateTime
ToShortTimeString()Returns a short string representation of the time component of a DateTime
ToString()Returns a string representation of a DateTime

Having A Go

  1. Write a program that allows the user to type in a date and get the day of the week for that date.
  2. Write a program that tells the user whether a year entered at the keyboard is a leap year.