Saturday, January 17, 2009

Adobe Flex 3: How to automatically display the current date in a Datefield component

The following code automatically fills in the current date in a Datafield object in Flex 3.

so you have this: datafield2.jpg instead of this: datafield1.jpg

The full mxml code:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" creationComplete="displayDate()">
	<mx:Script>
		<![CDATA[
			 public function displayDate():void {
            	                var now:Date = new Date();
				var day_int:int = now.getDate(); //gets day of the month
				var month_int:int = (now.getMonth()+1); // gets month. Months are given from 0 to 11, so you need to do +1 here
				var year_int:int = now.getFullYear(); // gets year

				var day_string:String;
				//display always 2 digits for a month, so '02' instead of just '2' for February
				if (day_int < 10) {
					day_string = "0" + day_int.toString();
				}
				else {
					day_string = day_int.toString();
				}

				var month_string:String;
				//display always 2 digits for a day, so '02' instead of just '2'
				if (month_int < 10) { 
					month_string = "0" + month_int.toString();
				}
				else {
					month_string = month_int.toString();
				}

				var year_string:String = year_int.toString();

				// note: this is displaying the date in the DD/MM/YYYY format, this same format is also set for the Datefield below!
				DateSelect.text = day_string + "/" + month_string + "/" + year_string;
			}
		]]>
	</mx:Script>
	<mx:DateField id="DateSelect" formatString="DD/MM/YYYY"/>

</mx:Application>
  1. Jack Sparrow

    Tuesday, April 28, 2009 - 07:27:56

    Please try the following:

    <?xml version=”1.0” encoding=”utf-8”?>
    <!– CurrentDate.mxml –>
    <mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute”>

    <!– Declare a DateFormatter and define format string–>
    <mx:DateFormatter id=”dateFormatter” formatString=”DD/MM/YYYY”/>

    <mx:HBox>
    <mx:Label text=”Enter Date:”/>
    <mx:DateField id=”myDate”
    formatString=”DD/MM/YYYY”
    text=”{dateFormatter.format(new Date())}”/>
    </mx:HBox>
    </mx:Application>

    Please refer DateFormatter documentation.