Date to String <-> String to Date

筅森魡賤 提交于 2019-12-18 05:55:31

问题


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.


回答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.




回答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");



回答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);
    }       
}


来源:https://stackoverflow.com/questions/3135829/date-to-string-string-to-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!