Spark formatters

Flex includes the following Spark classes for formatting dates, numbers and currencies:

The Spark formatters provide the following functionality:

  • Locale-specific formatting of dates, times, number, and currency amounts.

  • Locale-specific parsing of numbers and currency amounts.

  • Locale-specific string comparison. For more information, see Sorting and matching.

  • Locale-specific uppercase and lowercase string conversion.

The Spark formatters use the locale style property to determine how to format data based on the locale. The locale style is an inheritable style that you can set for the entire application or specifically for a particular formatter.

If a Spark formatter does not explicitly set the locale style, then it uses the value specified by the locale style of the application container. If you do not set the locale style property, the application uses the global default from the defaults.css style sheet, which defaults to en. For more information, see Setting the locale.

You can explicitly configure the formatter to use the default locale by setting the locale style to the constant value flash.globalization.LocaleID.DEFAULT.

Error handling in a Spark formatter

You call the format() method to format a value. By default, if the format() method fails, it returns null. However, you can use the errorText property of the formatter to define a String to return, as the following example shows:

<?xml version="1.0" encoding="utf-8"?>
<!-- formatters\sparkformatters\SparkFormatterError.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">
    <s:layout> 
        <s:VerticalLayout paddingTop="10" paddingLeft="5"/> 
    </s:layout> 
    
    <fx:Declarations> 
        <!-- Declare a Spark DateTimeFormatter and 
        define formatting parameters.--> 
        <s:DateTimeFormatter id="dateTimeFormatter" 
            dateTimePattern="month: MM, day: DD, year: YYYY"
            errorText="Invalid input value"/> 
    </fx:Declarations> 
    
    <s:Label text="Enter date (mm/dd/yyyy):"/> 
    <s:TextInput id="dob" text=""/> 
    
    <s:Label text="Formatted date: "/> 
    <s:TextInput id="formattedDate" 
        text="" width="300"
        editable="false"/> 
    
    <!-- Format and update the date.--> 
    <s:Button label="Format Input" 
        click="formattedDate.text=dateTimeFormatter.format(dob.text);"/> 
</s:Application>

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

Formatting numbers with a Spark formatter

The Spark NumberFormatter class provides basic formatting options for numeric data, including decimal formatting, thousands separator formatting, and negative sign formatting.

The format() method accepts a number or a number formatted as a String value, and returns the formatted string. When a number formatted as a String value is passed to the format() method, the function first uses the Number() function to convert the String to a Number object.

The following example uses the NumberFormatter class in an MXML file:
<?xml version="1.0" encoding="utf-8"?>
<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" minWidth="955" minHeight="600">
    <s:layout>
        <s:VerticalLayout paddingTop="10" paddingLeft="5"/>
    </s:layout>

    <fx:Script>
        <![CDATA[
            protected function button2_clickHandler(event:MouseEvent):void {
                displayVal.text = PrepForDisplay.format(bigNumber.text);
            }
        ]]>
    </fx:Script>

    
    <fx:Declarations>
        <!-- Declare and define parameters for the NumberFormatter.-->
        <s:NumberFormatter id="PrepForDisplay"
            fractionalDigits="3" 
            decimalSeparator="."
            groupingSeparator=","
            useGrouping="true"
            negativeNumberFormat="0"
            errorText="'{bigNumber.text}' is an invalid input value"/>
    </fx:Declarations>
    
    <!-- String to format.-->
    <s:TextInput id="bigNumber" text="Enter number"/>  
    <s:Button label="Format Value" 
        click="button2_clickHandler(event);"/>
    
    <!-- Display formatted value.-->
    <s:Label id="displayVal"/> 
</s:Application>

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

Formatting currency with a Spark formatter

The Spark CurrencyFormatter class provides the same features as the NumberFormatter class, plus a currency symbol. It also has additional properties to control the formatted result: currencySymbol, negativeCurrencyFormat, and positiveCurrencyFormat.

The format() method accepts a Number value or a number formatted as a String value and formats the resulting string. When a number formatted as a String value is passed to the format() method, the function first uses the Number() function to convert the String to a Number object.

The useCurrencySymbol property determines the currency symbol returned in the formatted String based on the locale style property. When the useCurrencySymbol property is set to true, the formatter returns the value of the currencySymbol property in the formatted String. When the useCurrencySymbol property is set to false, the formatter returns the value of the currencyISOCode property in the formatted String.

The following example uses the CurrencyFormatter class in an MXML file:
<?xml version="1.0" encoding="utf-8"?>
<!-- formatters\sparkformatters\SparkCurrencyFormatter.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">
    <s:layout>
        <s:VerticalLayout paddingTop="10" paddingLeft="5"/>
    </s:layout>
    
    <fx:Script>
        <![CDATA[
            protected function button1_clickHandler(event:MouseEvent):void {
                displayVal.text = Price.format(currVal.text);
            }
        ]]>
    </fx:Script>
    
    <fx:Declarations>
        <!-- Declare a CurrencyFormatter and define parameters.-->
        <s:CurrencyFormatter id="Price" 
            currencySymbol="$" 
            useCurrencySymbol="true"
            negativeCurrencyFormat="0"
            positiveCurrencyFormat="0"
            errorText="'{currVal.text}' is an invalid input value"/>
    </fx:Declarations>
    
    <!-- Enter currency value, then click the Button to format. -->
    <s:TextInput id="currVal" text="Enter value"/>
    <s:Button label="Format Value" 
        click="button1_clickHandler(event);"/>

    <!-- Display formatted value.-->
    <s:Label id="displayVal"/> 
    
</s:Application>

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

Formatting dates with a Spark formatter

The Spark DateTimeFormatter class gives you a wide range of combinations for displaying date and time information. The format() method accepts a Date object, which it converts to a String based on a user-defined pattern.

The format() method can also accept a String-formatted date. If you pass a String, the formatter first converts it to a Date object by using the Date constructor. The hour value in the String must be between 0 and 23, inclusive. The minutes and seconds value must be between 0 and 59, inclusive. If the format() method is unable to parse the String into a Date object, it returns null.

The following examples show possible input strings to the format() method:

"12/31/98" or "12-31-98" or "1998-12-31" or "12/31/1998" 
"Friday, December 26, 2005 8:35 am" 
"Jan. 23, 1989 11:32:25"

Using pattern strings

Use the dateTimePattern property of the DateTimeFormatter class to specify the string of pattern letters that determine the appropriate formatting. You compose a pattern string by using specific letter sequences. For example, “yyyy/MM”.

Note: By omitting a pattern string, the date is formatted using the default for the current locale. By specifying a pattern string, you override the default formatting. Information, such as month and day names, are still displayed correctly for the locale, but the order of elements in the formatted string is fixed by the specified pattern string.

You can include text and punctuation in the pattern string. However the characters from “a” to “z” and from “A” to “Z” are reserved as syntax characters. Enclose these characters in single quotes to include them in the formatted output string. To include a single quote, use two single quotes. The two single quotes may appear inside or outside a quoted portion of the pattern string.

When you create a pattern string, you usually repeat pattern letters. The number of repeated letters determines the presentation. For numeric values, the number of pattern letters is the minimum number of digits; shorter numbers are zero-padded to this amount. For example, the four-letter pattern string “yyyy” corresponds to a four-digit year value.

In cases where there is a corresponding mapping of a text description—for example, the name of a month—the full form is used if the number of pattern letters is four or more; otherwise, a short or abbreviated form is used, if available. For example, if you specify the pattern string “MMMM” for month, the formatter requires the full month name, such as “December”, instead of the abbreviated month name, such as “Dec”.

For time values, a single pattern letter is interpreted as one or two digits. Two pattern letters are interpreted as two digits.

The complete list of options to the pattern string is defined by the setDateTimePattern() method of the flash.globalization.DateTimeFormatter class.

The following table shows sample pattern strings and the resulting presentation:

Pattern

Result

EEEE, MMMM dd, yyyy h:mm:ss a (default)

Wednesday, December 01, 2010 3:06:43 PM

yyyy.MM.dd 'at' h:mm:ss

2010.12.01 at 3:19:44

EEE, MMM d, yy

Wed, Dec 1, 10

kk 'o''clock' a

15 o'clock PM

k:mm a

12:08 PM

K:mm a

0:08 PM

yyyy.MMMM.dd HH:mm:ss

2005.July.04 12:08:34

Example: Using the Spark DateFormatter class

The following example uses the DateTimeFormatter class in an MXML file for formatting a Date object as a String:
<?xml version="1.0" encoding="utf-8"?>
<!-- formatters\spark\SparkDateFormatter.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" minWidth="955" minHeight="600">
    <s:layout>
        <s:VerticalLayout paddingTop="10" paddingLeft="5"/>
    </s:layout>
    
    <fx:Script>
        <![CDATA[
            // Define variable to hold the date.        
            [Bindable]
            private var today:Date = new Date();        
        ]]>
    </fx:Script>
    
    <fx:Declarations>
        <!-- Declare a DateFormatter and define parameters.-->
        <s:DateTimeFormatter id="DateDisplay1" 
            dateTimePattern="MMMM d, yyyy"/>

        <s:DateTimeFormatter id="DateDisplay2" 
            dateTimePattern="hh:mm a"/>

        <s:DateTimeFormatter id="DateDisplay3" 
            dateTimePattern="hh:mm a, MMMM d, yyyy"/>

        <s:DateTimeFormatter id="DateDisplay4" 
            dateTimePattern="yyyy.MMMM.dd HH:mm:ss"/>
</fx:Declarations>
    
    <!-- Display the date in a Label control.-->
    <s:Label id="myTA1" text="{DateDisplay1.format(today)}"/> 

    <!-- Display the date in a Label control.-->
    <s:Label id="myTA2" text="{DateDisplay2.format(today)}"/> 

    <!-- Display the date in a Label control.-->
    <s:Label id="myTA3" text="{DateDisplay3.format(today)}"/> 

    <!-- Display the date in a Label control.-->
    <s:Label id="myTA4" text="{DateDisplay4.format(today)}"/> 
</s:Application>

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