Visual Basic Concepts

Using the DateTimePicker Control

The DateTimePicker control displays date and/or time information and acts as the interface through which users can modify date and time information. The control's display consists of fields that are defined by the control's format string. When the DateTimePicker is dropped down, a MonthView calendar is displayed.

The control has two different modes:

  • Dropdown Calendar mode (default) – enables the user to display a dropdown calendar that can be used to select a date.

  • Time Format mode – enables the user to select a field in the date display (i.e. the month, day, year, etc.) and press the up/down arrow to the right of the control to set its value.

You can use the control to display the date in various preset formats including Short Date (11/14/97), LongDate (Friday, November 14, 1997) and Time (7:00:00 PM). You can also specify custom formats using formatting strings, or create your own formats with .

DateTimePicker control in Dropdown Calendar Mode

DateTimePicker control in Time Format Mode

Possible Uses

  • To present date information where a restricted or specially formatted field is required, such as in a payroll or scheduling application.

  • To give users the ability to select a date with the click of a mouse instead of typing a date value.

Using the Two Modes of the Control

The DateTimePicker operates as a masked edit control for entering date and time values. Each part of the date or time is treated as a separate field within the edit portion of the control. As the user clicks on each field, it is highlighted and they can use the up and down arrow keys to increment or decrement the value of the field. The user can also type values directly into the control, where applicable.

The UpDown property determines which mode the control is in. When UpDown is set to False, the control is in Dropdown Calendar mode. (The default value) When the UpDown property is set to True, the DateTimePicker is in Time Format mode.

In Time Format mode, two scroll arrows appear on the right side of the control. The user can click these arrows with the mouse to increment or decrement the value of the currently selected field. In Dropdown Calendar mode, the control drops down a calendar that the user can use to select dates.

The dropdown calendar has most of the features of the MonthView control. See "Using The MonthView Control" for more information on how to set up and format the dropdown calendar portion of the DateTimePicker control.

Setting and Returning Dates

The currently selected date in the control is determined by the Value property. You can set the Value of the control before it is displayed (for example, at design time or in the Form_Load event) to determine which date will be initially selected in the control:

DTPicker1.Value = "10/31/97"

By default, the control's Value is set to the current date. If you change the DateTimePicker's Value in code, the control is automatically updated to reflect the new setting.

The Value property returns a raw date value, or a null value. The DateTimePicker control has several properties that return specific information about the displayed date:

  • The Month property returns the integer value (1-12) of the month containing the currently selected date.

  • The Day property returns the day number (1-31) currently selected.

  • The DayOfWeek property returns a value indicating the day of the week the selected date falls on (values correspond to the values of vbDayOfWeek constants.)

  • The Year property returns the year containing the selected date as an integer value.

  • The Week property returns the number of the week containing the selected date.

Use the Change event to determine when the user has changed the date value in the control.

Using The Checkbox to Select No Date

The CheckBox property makes it possible to specify whether the control returns a date. By default, CheckBox is set to False and the control always returns a date.

To enable the user to specify no date, set the CheckBox property to True (for example, if you are using the DateTimePicker to enter the completion date of a project but the project has not yet been completed).

When CheckBox is set to True, a small check box appears in the edit portion of the control to the left of the date and time. If the box is not checked, the Value property returns a null value. If the user checks this checkbox, the control returns the displayed date through its Value property.

Working With Date & Time Formats

The DateTimePicker gives you a tremendous amount of flexibility in formatting the display of dates and times in the control. You can use all the standard Visual Basic formatting strings, or you can create custom formats by using callback fields.

The Format property determines how the control formats the raw date value. You can choose from one of the predefined formatting options, or use the custom formatting feature of the control.

The CustomFormat property defines the format expression used to display the contents of the control. You specify a format string that tells the control how to format the date output. The DateTimePicker controls supports the following format strings:

String Description
d The one- or two-digit day.
dd The two-digit day. Single digit day values are preceded by a zero.
ddd The three-character day-of-week abbreviation.
dddd The full day-of-week name.
h The one- or two-digit hour in 12-hour format.
hh The two-digit hour in 12-hour format. Single digit values are preceded by a zero.
H The one- or two-digit hour in 24-hour format.
HH The two-digit hour in 24-hour format. Single digit values are preceded by a zero.
m The one- or two-digit minute.
mm The two-digit minute. Single digit values are preceded by a zero.
M The one- or two-digit month number.
MM The two-digit month number. Single digit values are preceded by a zero.
MMM The three-character month abbreviation.
MMMM The full month name.
s The one- or two- digit seconds.
ss The two-digit seconds. Single digit values are proceeded by a zero.
t The one-letter AM/PM abbreviation (that is, "AM" is displayed as "A").
tt The two-letter AM/PM abbreviation (that is, "AM" is displayed as "AM").
X A callback field that gives programmer control over the displayed field (see below.) Multiple 'X' characters can be used in series to signify unique callback fields.
y The one-digit year (that is, 1996 would be displayed as "6").
yy The last two digits of the year (that is, 1996 would be displayed as "96").
yyy The full year (that is, 1996 would be displayed as "1996").

You can add body text to the format string. For example, if you want the control to display the current date with the format "Today is: 05:30:31 Friday Nov 14, 1997". The format string you would use is "'Today is: 'hh':'m':'s ddddMMMdd', 'yyy". Body text must be enclosed in single quotes.

Creating Custom Formats with Callback Fields

One of the custom format fields described above is a callback field. A callback field allows you to customize the output of certain parts of a format string. To declare a callback field, you must include one or more 'X' characters (ASCII Code 88) anywhere in the body of the format string. Callback fields are displayed in left-to-right order.

When a new date is displayed in a format that includes one or more callback fields, The Format and FormatSize events are raised for each callback field. You can use the Format event to specify a custom response string, and the FormatSize event to determine the space needed to display the string. This behavior gives you complete control of how a callback field is displayed.

Each sequence of X’s has a unique meaning. For example, X might mean "st/nd/rd/th" (for "1st" "2nd" "3rd" "4th" etc) and "XX" may mean "first" "second" "third" "fourth" etc. These fields do not format the users’ text, they format the date into a displayable format.

For example, let's say you want to display the month in Spanish as well as English, using a format like this:

July (Julio) 29

You would create a format string that looked like this:

MMMM XXXX d

When processing the Format and FormatSize events, you can check which callback field is being called by comparing the input format sting with "XXXX". If the field string matches, an output string "(Julio)" can be built and the length of the output string can be supplied. The number of Xs is only used by an application to determine what text to supply for a callback field. When processing the FormatSize event, the size of the text can be programmatically calculated.

The Format event is called whenever the control needs to fill in the callback field, such as when the user selects a different date from that of the dropdown calendar. However, the FormatSize event is called only when there is a change to the format string (for instance, if you change it from "XX" to "XXXX".) This means that when you calculate the size of the callback field in the FormatSize event, you must take into account any possible value that can be returned by the Format event.

For example, you would use the following process to implement the callback field in the format string mentioned above.

  1. In the (General)(Declarations) section of the form, declare an array variable to hold the lookup table for the names of the Spanish months:

        Private sSpMonth(12) As String
    
  2. In the Load event of the form, populate the lookup table and set the DTPicker to use the custom format string:

        sSpMonth(0) = "Enero"
        sSpMonth(1) = "Febrero"
        sSpMonth(2) = "Marzo"
        sSpMonth(3) = "Abril"
        sSpMonth(4) = "Mayo"
        sSpMonth(5) = "Junio"
        sSpMonth(6) = "Julio"
        sSpMonth(7) = "Agusto"
        sSpMonth(8) = "Septiembre"
        sSpMonth(9) = "Octubre"
        sSpMonth(10) = "Noviembre"
        sSpMonth(11) = "Diciembre"
    
        DTPicker1.Format = dtpCustom
        DTPicker1.CustomFormat = "MMMM (XXX) dd, yy"
    
  3. In the FormatSize event, search through the list of possible return values to find the longest one. Specify this as the length of the formatted string. This will prevent clipping of the Spanish month name when the value in the control is changed.

        Private Sub DTPicker1_FormatSize(ByVal CallbackField As String,
        Size As Integer)
            Dim iMaxMonthLen As Integer
            Dim iC As Integer
                Select Case CallbackField
                Case "XXX"
                    iMaxMonthLen = 0
                    For iC = 0 To 11
                        If iMaxMonthLen < Len(sSpMonth(iC)) Then
                            iMaxMonthLen = Len(sSpMonth(iC))
                        End If
                    Next iC
                End Select
                Size = iMaxMonthLen
        End Sub
    
  4. In the Format event, return the appropriate value as the formatted string:

        Private Sub DTPicker1_Format(ByVal CallbackField As String,
        FormattedString As String)
            Select Case CallbackField
            Case "XXX"
                FormattedString = sSpMonth(DTPicker1.Month - 1)
            End Select
        End Sub
    

You can create unique callback fields by repeating the "X" character. Thus, the format string "XX dddd MMM dd', 'yyy XXX" contains two callback fields. You can use Select or If statements to process multiple callback strings in the Format and FormatSize events.

Callback fields are treated as valid fields, so the application must be prepared to handle the CallbackKeyDown event. You can use this event to process individual keystrokes in the callback field and to provide keystroke validation or automated entry completion. For example, if the user was entering a month and they had typed the letter "D", you could use the CallbackKeyDown event to fill in the callback field with the word "December."

Formatting the Calendar Control

There are many options for formatting the calendar drop-down portion of the control. All the properties of the DateTimePicker that are preceded by the word "Calendar" affect the formatting of the calendar drop down. These properties correspond to properties in the MonthView control. For example, the DateTimePicker's CalendarTitleTextColor property is comparable to the TitleTextColor property of the MonthView. See the topic Using The MonthView Control for more information about calendar formatting issues.

Keyboard Interface

The Calendar control can be manipulated with the keyboard. The following table describes the different actions you can perform with the control at run time.

Key Description
LEFT ARROW Selects the next field to the left. If this key is pressed when the left-most field is selected, the selection wraps to the right-most field.
RIGHT ARROW Selects the next field to the right. If this key is pressed when the right-most field is selected, the selection wraps to the left-most field.
UP ARROW Increments the value of the selected field.
DOWN ARROW Decrements the value of the selected field.
HOME Changes the value of the selected field to its upper limit.
END Changes the value of the selected field to its lower limit.
UP ARROW Increments the value for the selected field.
DOWN ARROW Decrements the value of the selected field.
PLUS (+) on Numeric Keypad Increments the value of the selected field.
MINUS (-) on Numeric Keypad Decrements the value of the selected field.

The following table describes the different actions you can perform while the dropdown calendar is displayed.

Key Description
LEFT ARROW Selects the next day
RIGHT ARROW Selects the previous day
UP ARROW Selects the same day of week in the previous week
DOWN ARROW Selects the same day of week in the next week
PAGE UP Scrolls the display to past months.
PAGE DOWN Scrolls the display to future months.
CTRL+PAGE UP Scrolls the display to the previous year.
CTRL+PAGE DOWN Scrolls the display to the next year.

Distribution Note   The DateTimePicker control is part of a group of ActiveX controls that are found in the MSCOMCT2.OCX file. To use the DateTimePicker control in your application, you must add the MSCOMCT2.OCX file to the project. When distributing your application, install the MSCOMCT2.OCX file in the user's Microsoft Windows System or System32 directory. For more information on how to add an ActiveX control to a project, see the Programmer's Guide.