Biyernes, Hunyo 3, 2011

Flex Date Formatter Class

I have a class that will automatically get the current year, month and day of a specified date and at the same time will format the date. This class very is easy to use. The code is given below:

//format the date from int to string. Just supply the date and the separator you want.
public function formatDate(date:int, separator:String):String
 {
     var year:String = String(date).substr(0, 4);
     var month:String = String(date).substr(4, 2);
     var day:String = String(date).substr(6, 2);
   
     return month + separator + day + separator + year;
 }
  example: var date_str:String=formatDate(20110603,' / ' );

The function above is just part of the class I am trying to give in this post. The complete code
of the class is given below:

import mx.controls.DateField;

 /*  Format Date function */

 public function formatDate(date:int, separator:String):String
 {
     var year:String = String(date).substr(0, 4);
     var month:String = String(date).substr(4, 2);
     var day:String = String(date).substr(6, 2);
    
     return month + separator + day + separator + year;
 }

 //format the date type to string
 public function formatDateToString(date:Date, separator:String):String
 {
    return DateField.dateToString(date, "YYYYMMDD"); 
 }

 public function getDate(date:String, separator:String):int
 {
     var tmp:Array = date.split(separator, 3);
    
     var year:String = tmp[2];
     var month:String = tmp[0];
     var day:String = tmp[1];
    
     return int(year+month+day);
 }

 public function getYear(date:int):int
 {
     return int(String(date).substr(0, 4));
 }

 public function getDay(date:int):int
 {
     return int(String(date).substr(4, 2));
 }

 public function getMonth(date:int):int
 {
     return int(String(date).substr(6, 2));
}

 
The date formatter class is very easy to use. Just import the class in your application:

        Example:  
            //import first the class in new application
                import libraries.Date.DateFormatter;
    
    Then after importing, you can used already the functions defined in the class to get the format of the date you want.