Tip on Formatting dates with the DateField Control in Flex.

We can specify a function to format the date displayed in the text field using labelFunction property of the DateField control. Function will take date and returns the string representation of the date, and in the function we can use the DateFormatter Class to format the date to our needs.

Now to parse the entered date as text we specify a parse function using the parseFunction property of the DateField control. Function takes two arguments, entered text and the formatString and returns a date object typically performing the reverse of the label function. DateField uses a default parse function DateField.stringToDate, but we can specify a custom one. If you don’t want to edit the DateField control then simply specify null to the property.

Example:

For example to represent dates in the editable DateField control in DD MMM YY [10 Feb 09] format, we make use of lableFunction, parseFunction properties of the DateField Control.

Solution:

Using two DateFormatters

<mx:DateFormatter id=”dtf1″ formatString=”DD MMM YY”/>
<mx:DateFormatter id=”dtf2″ formatString=”DD/MM/YY”/>

//the label function

[showmyads]

private function fnDtfLblFunct(date:Date):String
{
return dtf1.format(date);
}

//the parse function

private function fnDtfPrsFunct(valueString:String,formatString:String):Date
{
return new Date(DateField.stringToDate(dtf2.format(valueString),”DD/MM/YY”));
}

Now observe these two above functions and their input,output.

Run Demo

Download Code

Explore more on  DateField Class and DateFormatter Class and just look in to the code, You will do great, because as always told “smart developers always view source”.

Enjoy the post.

Advertisements

6 Responses to Tip on Formatting dates with the DateField Control in Flex.

  1. varun says:

    Hi Kumar,

    This post helped me a lot, thanks for the explanation and the code.keep up the good work.

    cheers,
    Varun.

  2. barry says:

    this is just p-o-s! especially in “return new Date(…” – why do you think they use here “new Date”? And stop copying from each other bad code! It becomes impossible to filter google results from this shit..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: