TECHNOLOGIES: DateTime Type | Manipulating DateTime Values
Working with the DateTime Type
By Ken Getz
Many applications you create will need to work with dates and times. The .NET Framework provides rich support for managing date and time values, and this article works through many common date and time issues. In the .NET Framework, the DateTime type represents dates and times and allows you to perform calculations. The TimeSpan type represents an elapsed period of time. If you're a VB or VBScript developer, you probably are well aware of the deficiencies in those environments when it comes to working with elapsed periods of time. The Date type in VB and VBScript appeared as though it could contain an elapsed time, but it had no real support for measuring the differences in two time values.
In this installment of Class Act (and the next) I'll focus on these two types and demonstrate many of the members of each type. I'll begin by taking a look at the DateTime type. Here are some facts about the DateTime type:
- DateTime is a structure, not a class. This means you needn't use the New keyword to create a new instance of this value type (as opposed to reference type) unless you want to use one of the DateTime structure's constructors.
- The DateTime type contains values ranging from midnight, Jan. 1, 0001, to 100 nanoseconds before midnight on Dec. 31, 9999.
- DateTime values measure time in 100-nanosecond units called ticks. Any DateTime value represents the number of ticks since midnight, Jan. 1, 0001.
- DateTime values represent a single instant in time, not a time span. To represent time spans, use the TimeSpan type. You can add a TimeSpan value to a DateTime value to get a date or time in the future. Or you can subtract two DateTime values to get a TimeSpan value.
- Calculations against a DateTime value (Add or Subtract, for instance) don't modify the original value. They return a new value with the requested modifications.
The sample project, DateTimeDemo.sln, allows you to try out most of the members of the DateTime type. For example, properties.aspx (shown in FIGURE 1) demonstrates many of the simple properties.
FIGURE 1: The properties.aspx page demonstrates most of the members of the DateTime and TimeSpan types.
Creating DateTime Values
You aren't required to use a DateTime constructor. Instead, you may assign a value into a DateTime type, like this:
Dim dt As DateTime
dt = #1/12/2002#
You also can take advantage of the DateTime structure's constructor procedures to create a new DateTime value filled in with a particular date and time. The DateTime type provides a number of different constructors to give you various ways in which to create a new DateTime object. You'll find several overloaded procedures with various sets of parameters. You can pass in any of:
- A Long value that indicates a number of ticks.
- Three Integer values that indicate the year, month, and day.
- Six Integer values to indicate the year, month, day, hour, minute, and second.
- Seven Integer values to indicate the year, month, day, hour, minute, second, and millisecond.
For example, you can create a new DateTime value like this:
' Specify a date by a number of ticks.
Dim dt As New DateTime(1234567)
' Specify year, month, and day.
Dim dtCurrent As New DateTime(2002, 1, 31)
You also can create a DateTime value by calling the shared Parse method. For example, you could create a new DateTime value by parsing the value in a TextBox control using this code:
Dim dt As DateTime
dt = DateTime.Parse(txtNow.Text)
The Parse method attempts to convert a text value containing a date or time into a DateTime value. By default, the Parse method uses the local language settings when parsing dates and times. You also can provide cultural information to have Parse do its job using information from a different locale.
Members of the DateTime Structure
The DateTime type provides a number of shared members, which means you don't need to access them through a specific DateTime instance. You refer to these members using the type name instead. FIGURE 2 lists the shared fields and properties. See main.aspx in the sample project for an example of these properties in use.
Largest DateTime value. Read-only.
Smallest DateTime value. Read-only.
Current local date and time.
Current local date (with time set to midnight).
Current date and time expressed as coordinated universal time (UTC).
FIGURE 2: Shared properties provided by the DateTime type.
To use any of the shared properties of the DateTime type, use the type itself, like this:
Dim dt As New DateTime()
dt = DateTime.Now
The main.aspx page includes code like this, with the Label controls filled in with DateTime values:
txtNow.Text = DateTime.Now.ToString
The DateTime type also provides a series of simple properties, as FIGURE 1 shows. A few of these require special consideration:
- Date returns just the date portion of the DateTime value. The time part is set to midnight on the selected date.
- TimeOfDay returns just the time portion of the DateTime value.
- Year, Month, Day, Hour, Minute, Second, and Millisecond return the corresponding portion of the DateTime value.
- Ticks returns the number of ticks (100 nanoseconds) since midnight on Jan. 1, 0001, up to the specified DateTime value.
- DayOfYear returns the ordinal position within the calendar year corresponding to the DateTime value. (DayOfYear and Day values only will correspond for dates in January, of course.)
Converting to and from DateTime Values
The DateTime type provides a number of methods that convert from a specific DateTime value to another value or to different types. FIGURE 3 shows the Conversion.aspx page demonstrating these methods.
FIGURE 3: The DateTime type provides several methods that convert DateTime values to other types or values.
The conversion methods break down into several groupings:
- ToFileTime converts a DateTime value into a file-system time. The Windows file system uses a specialized format for its file times, and this method will convert it for you. (Use the FromFileTime method to convert from a file-system time to a DateTime value.)
- ToLocalTime assumes the DateTime value is in UTC time (also known as Greenwich Mean Time) and converts it to the local time using the current computer's locale. (In the sample page shown in FIGURE 3, the current locale is California, which is UTC-8, or eight hours earlier than UTC time.)
- ToUniversalTime works in just the opposite way. It assumes the DateTime value is local and converts it to UTC (in the sample case, by adding eight hours.)
- ToOADate manages conversion between DateTime values and date and time values used by OLE Automation and COM (hence the name, OADate), as well as Visual Basic 6. In COM and VB6, date and time values are stored as doubles, so this method returns a double. (Use the FromOADate method, discussed later in this article, to retrieve a DateTime value from VB6 or COM.)
- ToLongDateString, ToLongTimeString, ToShortDateString, ToShortTimeString, and ToString all convert the DateTime value into string formats by using the current locale of the computer to determine the format to use. The ToString method can accept a format specifier as a parameter. See the documentation for more information.
To use these instance methods, you must start with a DateTime value, like this:
Dim dt As New DateTime()
Dim dtUTC As New DateTime()
dt = DateTime.Now
dtUTC = dt.ToUniversalTime()
Performing Calculations on DateTime Values
The DateTime type provides a series of calculation functions, demonstrated by Calculation.aspx in the sample project. These functions include AddDays, AddHours, AddMilliseconds, AddMinutes, AddMonths, AddSeconds, and AddTicks. Each of these methods works in the same way: You supply a DateTime value, and you call the method of that value. You pass, as a parameter, the number of the specified unit you want to add or subtract. For example, you might write code like this:
Dim dt As New DateTime(1999, 2, 12)
' Calculate the value three years later.
dt = dt.AddYears(3)
Finally, the DateTime type provides a few shared methods. You can use them as methods of the type rather than as methods of a particular instance. SharedMethods.aspx, shown in FIGURE 4, shows three of these shared methods:
- DaysInMonth - You supply the year and the month (as integers), and this method returns the number of days in the month.
- IsLeapYear - You supply the year, and this method returns a Boolean value indicating whether the year was a leap year.
- FromOADate - You supply a double, and this method returns a DateTime type corresponding to the value, which ostensibly came from COM or VB6.
FIGURE 4: The DateTime type provides a few useful shared methods.
To use these methods, you might write code like this:
Dim blnIsLeapYear As Boolean
blnIsLeapYear = DateTime.IsLeapYear(Today.Year)
You'll find that you can use the DateTime type to solve all sorts of programming problems. The .NET Framework developers contemplated the issues developers face and attempted to add all the capabilities necessary to perform any type of date calculation.
I'll end this installment with a homework assignment. You've got a month to complete it. In your free time, use the DateTime type to create one or more of the following functions:
- FirstDayInMonth - Given a date, return a date representing the first day in the month.
- LastDayInMonth - Given a date, return a date representing the last day in the month.
- NextAnniversary - Given a date, return the next anniversary of that date. For example, given someone's birth date, calculate the next occurrence of it.
- Age - Given a birth date, calculate the current age.
You'll have to grade your own assignment, of course!
This column was adapted from courseware originally written by the author for Application Developer's Training Company (http://www.appdev.com).
The files referenced in this article are available for download.
Ken Getz is a senior consultant with MCW Technologies and splits his time between programming, writing, and training. He specializes in tools and applications written in Visual Studio .NET and Visual Basic .NET. Ken is co-author of several books, including ASP.NET Developer's Jumpstart with Paul D. Sheriff, Access Cookbook with Andy Baron and Paul Litwin, Access 2002 Developer's Handbook with Paul Litwin and Mike Gunderloy, and VBA Developer's Handbook 2nd Ed. with Mike Gilbert. Ken co-wrote the training materials for AppDev's VB .NET, ASP.NET, Access 97 and 2000, Visual Basic 5.0, and Visual Basic 6.0 classes. He frequently speaks at technical conferences, including Microsoft's TechEd and Informant Communications Group's conferences on Office and ASP.NET. Readers may contact Ken at mailto:[email protected].
Tell us what you think! Please send any comments about this article to [email protected]. Please include the article title and author.