DateChooser and DateField controls

The DateChooser and DateField controls are part of the MX component set. There is no Spark equivalent.

The DateChooser and DateField controls let users select dates from graphical calendars. The DateChooser control user interface is the calendar. The DateField control has a text field that uses a date chooser popup to select the date as a result. The DateField properties are a superset of the DateChooser properties.

For complete reference information, see DateChooser and DateField in the ActionScript 3.0 Reference for the Adobe Flash Platform.

About the DateChooser control

The DateChooser control displays the name of a month, the year, and a grid of the days of the month. It contains columns labeled for the days of the week. This control is useful in applications where you want a continually visible calendar. The user can select a single date from the grid. The control contains forward and back arrow buttons to let you change the month and year. You can disable the selection of certain dates, and limit the display to a range of dates.

The following image shows a DateChooser control:

Changing the displayed month does not change the selected date. Therefore, the currently selected date is not always visible. The DateChooser control resizes as necessary to accommodate the width of the weekday headings. Therefore, if you use day names, instead of letters, as headings, the calendar is wide enough to show the full day names.

About the DateField control

The DateField control is a text field that displays the date with a calendar icon on its right side. When a user clicks anywhere inside the bounding box of the control, a date chooser that is identical to the DateChooser control pops up. If no date has been selected, the text field is blank and the current month is displayed in the date chooser.

When the date chooser is open, users can click the month scroll buttons to scroll through months and years, and select a date. When the user selects a date, the date chooser closes and the text field displays the selected date.

This control is useful in applications where you want a calendar selection tool, but want to minimize the space that the date information takes up.

The following example shows two images of a DateField control. On the left is the DateField control with the date chooser closed; the calendar icon appears on the right side of the text box. To the right is a DateField control with the date chooser open:

You can use the DateField control anywhere you want a user to select a date. For example, you can use a DateField control in a hotel reservation system, with certain dates selectable and others disabled. You can also use the DateField control in an application that displays current events, such as performances or meetings, when a user selects a date.

Creating a DateChooser or DateField control

You define a DateChooser control in MXML by using the <mx:DateChooser> tag. You define a DateField control in MXML by using the <mx:DateField> tag. Specify an id value if you intend to refer to a component elsewhere in your MXML, either in another tag or an ActionScript block.

The following example creates a DateChooser control; to create a DateField control, simply change <mx:DateChooser> to <mx:DateField>. The example uses the change event of the DateChooser control to display the selected date in several different formats.

<?xml version="1.0"?>
<!-- controls\date\DateChooserEvent.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx">
    <fx:Script>
        <![CDATA[

        import mx.events.CalendarLayoutChangeEvent;
        
        private function useDate(eventObj:CalendarLayoutChangeEvent):void {
            // Make sure selectedDate is not null.
            if (eventObj.currentTarget.selectedDate == null) {
                return 
            }

            //Access the Date object from the event object.         
            day.text=eventObj.currentTarget.selectedDate.getDay();
            date.text=eventObj.currentTarget.selectedDate.getDate();
            month.text=eventObj.currentTarget.selectedDate.getMonth() + 1;
            year.text=eventObj.currentTarget.selectedDate.getFullYear();
            
            wholeDate.text= (eventObj.currentTarget.selectedDate.getMonth() + 1) +
                "/" + (eventObj.currentTarget.selectedDate.getDate() +            
                "/" + eventObj.currentTarget.selectedDate.getFullYear());
        }
        ]]>
    </fx:Script>

    <mx:DateChooser id="date1" change="useDate(event)"/>

    <s:Form x="200">
        <s:FormItem label="Day of week">
            <s:TextInput id="day" width="100"/>
        </s:FormItem>
        <s:FormItem label="Day of month">
            <s:TextInput id="date" width="100"/>
        </s:FormItem>
        <s:FormItem label="Month">
            <s:TextInput id="month" width="100"/>
        </s:FormItem>
        <s:FormItem label="Year">
            <s:TextInput id="year" width="100"/>
        </s:FormItem>
        <s:FormItem label="Date">
            <s:TextInput id="wholeDate" width="100"/>
        </s:FormItem>
    </s:Form>      
</s:Application>

The executing SWF file for the previous example is shown below:

Notice that the first line of the event listener determines if the selectedDate property is null. This check is necessary because selecting the currently selected date while holding down the Control key deselects it, sets the selectedDate property to null, then dispatches the change event.

Note: The code that determines the value of the wholeDate field adds 1 to the month number because the DateChooser control uses a zero-based month system. In this system, January is month 0 and December is month 11.

Using the Date class

The DateChooser and DateField controls use the selectedDate property to store the currently selected date, as an object of type Date. You can create Date objects to represent date and time values, or access the Date in the selectedDate property.

The Date class has many methods that you can use to manipulate a date. For more information on the Date class, see the ActionScript 3.0 Reference for the Adobe Flash Platform.

In MXML, you can create and configure a Date object by using the <mx:Date> tag. This tag exposes the setter methods of the Date class as MXML properties so that you can initialize a Date object. For example, the following code creates a DateChooser control and sets the selected date to April 10, 2005. Notice that months are indexed starting at 0:

<mx:DateChooser id="date1"> 
        <mx:selectedDate> 
            <fx:Date month="3" date="10" fullYear="2005"/> 
        </mx:selectedDate> 
</mx:DateChooser>     

The following example uses inline ActionScript to set the initial selected date for a DateField control:

<mx:DateField id="date3" selectedDate="{new Date (2005, 3, 10)}"/>

You can also set the selectedDate property in a function, as the following example shows:

<fx:Script> 
    <![CDATA[ 
        private function initDC():void { 
            date2.selectedDate=new Date (2005, 3, 10);         
        } 
    ]]> 
</fx:Script> 
 
<mx:DateChooser id="date2" creationComplete="initDC();"/>

You can use property notation to access the ActionScript setter and getter methods of the selectedDate property Date object. For example, the following line displays the four-digit year of the selected date in a text box:

<s:TextInput text="{date1.selectedDate.fullYear}"/> 

Specifying header, weekday, and today’s day text styles

The following date chooser properties let you specify text styles for regions of the control:

  • headerStyleName

  • weekDayStyleName

  • todayStyleName

These properties let you specify styles for the text in the header, weekday list, and today’s date. You cannot use these properties to set non-text styles such as todayColor.

The following example defines a DateChooser control that has bold, blue header text in a 16-pixel Times New Roman font. The day-of-week headers are in bold, italic, green, 15-pixel Courier text, and today’s date is bold, orange, 12-pixel Times New Roman text. Today’s date background color is gray, and is set directly in the <mx:DateChooser> tag.

<?xml version="1.0"?>
<!-- controls\date\DateChooserStyles.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx">
    
    <fx:Style>
        .myHeaderStyle{
            color:#6666CC; 
            font-family:Times New Roman, Times, serif;
            font-size:16px; font-weight:bold;}
        .myTodayStyle{
            color:#CC6633; 
            font-family:Times New Roman, Times, serif;
            font-size:12px; font-weight:bold;}
        .myDayStyle{
            color:#006600; 
            font-family:Courier New, Courier, mono;
            font-size:15px; font-style:italic; font-weight:bold;}
    </fx:Style>

    <mx:DateChooser 
        headerStyleName="myHeaderStyle" 
        todayStyleName="myTodayStyle" 
        todayColor="#CCCCCC"
        weekDayStyleName="myDayStyle"/>
</s:Application>

The executing SWF file for the previous example is shown below:

Specifying selectable dates

The DateChooser control has the following properties that let you specify which dates a user can select:

Property

Description

disabledDays

An array of days of the week that the user cannot select. Often used to disable weekend days.

disabledRange

An array of dates that the user cannot select. The array can contain individual Date objects, objects specifying date ranges, or both.

selectableRange

A single range of dates that the user can select. The user can navigate only among the months that include this range; in these months any dates outside the range are disabled. Use the disabledRange property to disable dates within the selectable range.

The following example shows a DateChooser control that has the following characteristics:

  • The selectableRange property limits users to selecting dates in the range January 1 - March 15, 2006. Users can only navigate among the months of January through March 2006.

  • The disabledRanges property prevents users from selecting January 11 or any day in the range January 23 - February 10.

  • The disabledDays property prevents users from selecting Saturdays or Sundays.

<?xml version="1.0"?>
<!-- controls\date\DateChooserSelectable.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx">
    
  <mx:DateChooser 
    selectableRange="{{rangeStart: new Date(2006,0,1),
        rangeEnd: new Date(2006,2,15)}}"
    disabledRanges="{[new Date(2006,0,11), 
        {rangeStart: new Date(2006,0,23), rangeEnd: new Date(2006,1,10)}]}"
    disabledDays="{[0,6]}"/>
</s:Application>

The executing SWF file for the previous example is shown below:

Setting DateChooser and DateField properties in ActionScript

Properties of the DateChooser and DateField controls take values that are scalars, Arrays, and Date objects. While you can set most of these properties in MXML, it can be easier to set some in ActionScript.

For example, the following code example uses an array to set the disabledDays property. Sunday (0) and Saturday (6) are disabled, which means that they cannot be selected in the calendar. This example sets the disabledDays property in two different ways, by using tags and by using tag attributes:

<?xml version="1.0"?>
<!-- controls\date\DateChooserDisabledOption.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx">
    
    <!-- Use tags.-->
    <mx:DateField>
            <mx:disabledDays>
                <fx:Number>0</fx:Number>
                <fx:Number>6</fx:Number>
            </mx:disabledDays>
    </mx:DateField>     

    <!-- Use tag attributes.-->
    <mx:DateField disabledDays="[0,6]"/>
</s:Application>

The executing SWF file for the previous example is shown below:

The following example sets the dayNames, firstDayOfWeek, headerColor, and selectableRange properties of a DateChooser control by using an initialize event:

<?xml version="1.0"?>
<!-- controls\date\DateChooserInitializeEvent.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx">
    <fx:Script>
        <![CDATA[
            import mx.events.DateChooserEvent;

            private function dateChooser_init():void {
                myDC.dayNames=['Sun', 'Mon', 'Tue', 
                    'Wed', 'Th', 'Fri', 'Sat'];
                myDC.firstDayOfWeek = 3;
                myDC.setStyle("headerColor", 0xff0000);
                myDC.selectableRange = {rangeStart: new Date(2009,0,1), 
                    rangeEnd: new Date(2012,0,10)};
            }
        
            private function onScroll():void {
                myDC.setStyle("fontStyle", "italic");
            }
        ]]>
    </fx:Script>

    <mx:DateChooser id="myDC" 
        width="200" 
        creationComplete="dateChooser_init();" 
        scroll="onScroll();"/>
</s:Application>

The executing SWF file for the previous example is shown below:

To set the selectableRange property, the code creates two Date objects that represent the first date and last date of the range. Users can only select dates within the specified range. This example also changes the fontStyle of the DateChooser control to italics after the first time the user scrolls it.

You can select multiple dates in a DateChooser control by using the selectedRanges property. This property contains an Array of objects. Each object in the Array contains two dates: a start date and an end date. By setting the dates within each object to the same date, you can select any number of individual dates in the DateChooser.

The following example uses an XML object to define the date for the DateChooser control. It then iterates over the XML object and creates an object for each date. These objects are then used to determine what dates to select in the DateChooser:

<?xml version="1.0" encoding="utf-8"?>
<!-- controls\date\ProgrammaticDateChooserSelector.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx" 
    creationComplete="init()">
    <fx:Script>
        <![CDATA[
            private function init():void {
                dc1.displayedMonth = 1;
                dc1.displayedYear = 2008;
            }           
            
            public function displayDates():void {
                var dateRanges:Array = [];
                for (var i:int=0; i<shows.show.length(); i++) { 
                    var cDate:Date = 
                        new Date(shows.show[i].showDate.toString());           
                    var cDateObject:Object = 
                        {rangeStart:cDate, rangeEnd:cDate};
                    dateRanges.push(cDateObject);
                }
                dc1.selectedRanges = dateRanges;
            }           
        ]]>
    </fx:Script>

    <!-- Define the data for the DateChooser -->    
    <fx:Declarations>
    <fx:XML id="shows" format="e4x">
        <data>
            <show>
               <showID>1</showID>
                <showDate>02/28/2008</showDate>
                <showTime>10:45am/11:15am</showTime>
            </show>
            <show>
                <showID>2</showID>
                <showDate>02/23/2008</showDate>
                <showTime>7:00pm</showTime>
            </show>
        </data>
    </fx:XML>
    </fx:Declarations>
 
    <mx:DateChooser id="dc1" 
        showToday="false" 
        creationComplete="displayDates();"/>
    
</s:Application>

The executing SWF file for the previous example is shown below:

Formatting dates with the DateField control

You can use the formatString property of the DateField control to format the string in the control’s text field. The formatString property can contain any combination of "MM", "DD", "YY", “YYYY”, delimiter, and punctuation characters. The default value is "MM/DD/YYYY".

In the following example, you select a value for the formatString property from the drop-down list:

<?xml version="1.0"?>
<!-- controls\date\DateFieldFormat.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx">
    
    <mx:HBox>
        <mx:ComboBox id="cb1">
            <mx:ArrayCollection>
                <fx:String>MM/DD/YY</fx:String>
                <fx:String>MM/DD/YYYY</fx:String>
                <fx:String>DD/MM/YY</fx:String>
                <fx:String>DD/MM/YYYY</fx:String>
                <fx:String>DD MM, YYYY</fx:String>
            </mx:ArrayCollection>     
        </mx:ComboBox>
    
        <mx:DateField id="date2" 
            editable="true" 
            width="100" 
            formatString="{cb1.selectedItem}"/>      
    </mx:HBox>        
</s:Application>

The executing SWF file for the previous example is shown below:

The DateField control also lets you specify a formatter function. A formatter function converts the date to a string in your preferred format for display in the control’s text field. The DateField labelFunction property and the Spark DateTimeFormatter class help you format dates.

By default, the date in the DateField control text field is formatted in the form "MM/DD/YYYY". You use the labelFunction property of the DateField control to specify a function to format the date displayed in the text field and return a String containing the date. The function has the following signature:

public function formatDate(currentDate:Date):String { 
    ... 
    return dateString; 
}

You can choose a different name for the function, but it must take a single argument of type Date and return the date as a String for display in the text field. The following example defines the function formatDate() to display the date in the form dd-mm-yyyy, such as 03-12-2011. This function uses a Spark DateTimeFormatter object to do the formatting:

<?xml version="1.0"?>
<!-- controls\date\DateChooserFormatter.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx">

    <fx:Script>
        <![CDATA[
            private function formatDateTime(date:Date):String {
                return dtf.format(date);
            }       
        ]]>
    </fx:Script>

    <fx:Declarations>
        <s:DateTimeFormatter id="dtf" dateTimePattern="MM-dd-yyyy"/>
    </fx:Declarations>
    
    <mx:DateField id="df" labelFunction="formatDateTime" parseFunction="{null}"/>
</s:Application>

The executing SWF file for the previous example is shown below:

The parseFunction property specifies a function that parses the date entered as text in the text field of the DateField control and returns a Date object to the control. If you do not allow the user to enter a date in the text field, set the parseFunction property to null when you set the labelFunction property.

If you want to let the user enter a date in the control’s text field, specify a function to the parseFunction property that converts the text string to a Date object for use by the DateField control. If you set the parseFunction property, it should typically perform the reverse of the function specified to the labelFunction property.

The function specified to the parseFunction property has the following signature:

public function parseDate(valueString:String, inputFormat:String):Date { 
    ... 
    return newDate 
}

Where the valueString argument contains the text string entered by the user in the text field, and the inputFormat argument contains the format of the string. For example, if you only allow the user to enter a text string by using two characters for month, day, and year, then pass "MM/DD/YY" to the inputFormat argument.

User interaction

The date chooser includes arrow buttons that let users move between months. Users can select a date with the mouse by clicking the desired date.

Clicking a forward month arrow advances a month; clicking the back arrow displays the previous month. Clicking forward a month on December, or back on January, moves to the next (or previous) year. Clicking a date selects it. By default, the selected date is indicated by a green background around the date and the current day is indicated by a black background with the date in white. Clicking the currently selected date deselects it.

The following keystrokes let users navigate DateChooser and DateFieldcontrols:

Key

Use

Left Arrow

Moves the selected date to the previous enabled day in the month. Does not move to the previous month. Use the Shift key plus the Left Arrow key to access disabled days.

Right Arrow

Moves the selected date to the next enabled day in the month. Does not move to the next month. Use the Shift key plus the Right Arrow key to access disabled days.

Up Arrow

Moves the selected date up the current day of week column to the previous enabled day. Does not move to the previous month. Use the Shift key plus the Up Arrow key to access disabled days.

Down Arrow

Moves the selected date down the current day of week column to next enabled day. Does not move to the next month. Use the Shift key plus the Down Arrow key to access disabled days.

Page Up

Displays the calendar for the previous month.

Page Down

Displays the calendar for the next month.

Home

Moves the selection to the first enabled day of the month.

End

Moves the selection to the last enabled day of the month.

+

Move to the next year.

-

Move to the previous year.

Control+Down Arrow

DateField only: open the DateChooser control.

Control+Up Arrow

DateField only: close the DateChooser control.

Escape

DateField only: cancel operation.

Enter

DateField only: selects the date and closes the DateChooser control.

Note: The user must select the control before using navigation keystrokes. In a DateField control, all listed keystrokes work only when the date chooser is displayed.