At times working with dates in code can be a little tricky. Four years ago the date data types in code caused a panic as the new millennium arrived. It would behoove anyone working with .NET to have a firm grasp on the nuances of working with dates. To that end, we present this excerpt from Kate Gregory's article "The .NET System Namespace", provided courtesy of InformIT. In it Gregory provides a brief overview of the DateTime structure in .NET.
The DateTime structure represents a date or a time, or both. It has a number of useful constructors to create instances using a numeric date and time, or a number of ticks (useful when you're working with older C++ code). Here are some examples:
DateTime now = DateTime::Now;
It can be intimidating to remember the parameters to the seven-integer constructor, but it's simple when you realize they go from largest to smallest: year, month, day, hour, minute, second, and millisecond. The millisecond parameter is optional and if you want, you can omit all the time parameters completely.
On September 17, 2003, this code produces the following output:
Monday, January 01, 0001
9/28/2003 2:30 PM
9/17/2003 1:17:41 PM
It matters that DateTime is a structure, not a class, because it is managed data. Managed classes can only be allocated on the heap with new; managed structures can only be allocated on the stack as in these examples. To get the individual parts of a date, use these properties:
- Day: The day of the month
- Month: 1 to 12
- Year: Always four digits
- Hour: 0 to 23
- DayOfWeek: 0 means Sunday
- Format: Creates a string based on the time and date, using a format string
The format string passed to Format() is either a single character representing one of a number of "canned" formats, or a custom format string. The most useful canned formats include
- d: A short date, such as 12/19/00
- D: A long date, such as Tuesday, December 19, 2000
- f: A full time and date, such as Tuesday, December 19, 2000 17:49
- g: A general time and date, such as 12/19/00 17:49
- s: A sortable time and date, such as 2000-12-19 17:49:03
- t: A short time, such as 17:49
- T: A long time, such as 17:49:03
If none of the canned formats has what you need, you can make your own by passing in strings such as "MMMM d, yy" for "December 3, 02" or whatever else you desire. You can find all the format strings in the help installed with Visual Studio.
You can read more about the .NET system namespace over at InformIT.