Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date to String <-> String to Date

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.

like image 412
Tim Avatar asked Jun 28 '10 20:06

Tim


3 Answers

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.

like image 103
Ryan Lynch Avatar answered Oct 05 '22 10:10

Ryan Lynch


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");
like image 26
Shua Avatar answered Oct 05 '22 12:10

Shua


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);
    }       
}
like image 31
Vasyl Avatar answered Oct 05 '22 11:10

Vasyl