Date to String <-> String to Date

25,007

Solution 1

Have you seen the DateFormatter class?

Example:

import mx.formatters.DateFormatter;

private var dateFormatter:DateFormatter;

private function init():void
{
    dateFormatter = new DateFormatter();
    dateFormatter.formatString = 'DD.MM.YYYY HH:NN:SS'
}

public function dateToString(d:Date):String
{
    return dateFormatter.format(d);
}

public function stringToDate(s:String):Date
{
    return dateFormatter.parseDateString(s);
}

It looks like somebody was asleep the day the wrote Flex 3.2, because DateFormatter::parseDateString is a protected function. It looks like they fixed that by 3.5.

Solution 2

I'm adding this because the stringToDate function does not work on answer above and the simple wrapper doesn't allow you to specify the input string format. The wrapper is actually no longer need since the function is now static, but you still have the same issue. I would recommend instead using the following static function from the DateField Class.

//myObject.CreatedDate = "10022008"

var d:Date = DateField.stringToDate(myObject.CreatedDate, "MMDDYYYY");

Solution 3

You can convert String to Date with DateFormatter::parseDateString, but this method is protected(?). To access method DateFormatter::parseDateString just write a simple wrapper:

import mx.formatters.DateFormatter;

public class DateFormatterWrapper extends DateFormatter
{
    public function DateFormatterWrapper()
    {
        super();
    }

    public function parseDate(str:String):Date
    {
        return parseDateString(str);
    }       
}
Share:
25,007
Tim
Author by

Tim

still learning :-)

Updated on October 07, 2020

Comments

  • Tim
    Tim almost 4 years

    I get a Date of my database and I need to show it as a String. So in Flex I do this:

    public static function dateToString(cDate:Date):String {
            return cDate.date.toString()+"."+
                cDate.month.toString()+"."+
                cDate.fullYear.toString()+" "+
                cDate.hours.toString()+":"+
                cDate.minutes.toString()+":"+
                cDate.seconds.toString();
    }
    

    But I get for example the result:

    13.7.2010 0:0:15

    How can I fill the day, month, hours, minutes, seconds with padded 0?

    And, I go back from String to Date with:

    DateField.stringToDate(myTextInput.text, "DD.MM.YYYY HH:MM:SS");
    

    Is this correct? I want to have a Date which I will transfer via BlazeDS to a J2EE Backend, but I only see in the database then a null value. So something is going wrong...

    Best Regards.