2010-06-28 120 views
7

我得到我的數據庫的日期,我需要顯示它作爲一個字符串。 所以Flex中我這樣做:日期到字符串<->字符串到日期

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(); 
} 

,但我得到例如結果:

2010年7月13日0:0:15

我怎樣才能填補日,月,小時,分鐘,帶填充0的秒?

而且,我回去從字符串到日期的搭配:

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

這是正確的嗎?我想要一個Date,我將通過BlazeDS傳輸到J2EE後端,但是我只能在數據庫中看到空值。所以出事了......

最好的問候。

回答

19

你見過DateFormatter類嗎?

例子:

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

它看起來像有人睡着了當天寫的Flex 3.2,因爲DateFormatter::parseDateString是受保護的功能。看起來他們通過3.5修正了這個問題。

+2

方法stringToDate不起作用,因爲它是受保護的方法。我正在使用Flex 4. – Tim 2010-07-12 17:03:24

+0

爲什麼在Flash CS4中會報錯,提示找不到定義mx.formatters.DateFormatter – 2012-03-28 08:51:38

+0

'parseDateString()'不接受也不考慮格式化字符串,因此如果字符串被正確轉換。 – splash 2013-09-09 09:17:24

5

您可以使用DateFormatter::parseDateString將字符串轉換爲日期,但此方法受保護(?)。要訪問方法DateFormatter::parseDateString只寫一個簡單的包裝:

import mx.formatters.DateFormatter; 

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

    public function parseDate(str:String):Date 
    { 
     return parseDateString(str); 
    }  
} 
+0

出色的伴侶,擁有這種受保護的方法。 :) – 2013-04-26 12:37:41

7

我加入這個,因爲stringToDate功能不上回答上面的工作和簡單的包裝不允許你指定的輸入字符串格式。包裝實際上不再需要,因爲函數現在是靜態的,但你仍然有同樣的問題。我會推薦使用DateField類中的以下靜態函數。

//myObject.CreatedDate = "10022008" 

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