2011-05-19 74 views
0

我想要使用標準類DateFormat其子類SimpleDateFormat要編寫一個名爲convert的方法,它將以dd.mm.yy的形式返回字符串:將GregorianCalendar傳遞給具體的日期格式化日期使用格式類(或其他如果)

public String convert (Calendar gc) { ... } 

例如,當myGC是代表2006年12月25日一GregorianCalendar變量,String s = convert(myGC);應該設置s到字符串「06年12月25日」。

,我有麻煩寫這個

+0

「我在編寫轉換方法時遇到了麻煩」 - 也許你想向我們展示你所嘗試過的,並告訴我們代碼有什麼問題? – 2011-05-19 22:27:09

回答

0

一個轉換方法,爲什麼不使用像這樣的"dd.MM.yy"在SimpleDateFormat的一種模式?

DateFormat dateFormatter = new SimpleDateFormat("dd.MM.yy"); 
String myDate = dateFormatter.format(cal.getTime()); 
0
public String convert(Calendar c) { 
    return new SimpleDateFormat("dd.MM.yy").format(c.getTime()); 
} 

最終你會想這SimpleDateFormat的存儲作爲成員(例如)如果性能成爲一個問題。

+0

...但要注意併發性,如果它可能是一個問題(當存儲爲成員時) – planetjones 2011-05-19 22:30:59

+0

Commons lang有一個線程安全的兼容版本,稱爲FastDateFormat – MJB 2011-05-19 23:15:08