2011-04-11 46 views

回答

86

試試這個:

Calendar cal = new GregorianCalendar(); 
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); 
dateFormat.setTimeZone(cal.getTimeZone()); 
System.out.println(dateFormat.format(cal.getTime())); 
+0

添加了來自JamesKingston的答案缺少的一步。謝謝! – janhink 2014-09-19 06:38:47

+1

不添加時區有什麼影響? – kamaci 2014-10-01 09:25:18

+2

@kamaci查看JamesKingston的回答下的評論。只有當您的日曆對象基於與系統默認時區不同的時區時纔有意義,並且您希望它在該日曆的時區中進行打印。如果不設置時區,它將使用默認的系統時區。如果這與日曆的時區相同,則設置時區沒有區別。請注意,JamesKingston的答案也適用 - 告訴dateFormat使用哪個日曆意味着它將知道使用日曆的時區。 – ToolmakerSteve 2015-09-07 09:11:28

3

Calendar.getTime()返回一個可以與SimpleDateFormat一起使用的日期。

3

只需致電calendar.getTime()並將產生的Date對象傳遞給format方法。

31

相等的回答是缺少一個步驟

Calendar cal = new GregorianCalendar(); 
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); 
#---- This uses the provided calendar for the output ----- 
dateFormat.setCalendar(cal); 
System.out.println(dateFormat.format(cal.getTime())); 
+1

+1,因爲答案是最完整的一個。如果沒有此方法調用,將使用默認日曆進行格式設置。 (但是這個問題沒有具體說明哪個日曆應該用於格式化。) – Robert 2012-08-16 03:09:27

+2

對於這種情況,這並不重要,但是如果你想做的事情如: 'cal.setTimeZone(TimeZone.getTimeZone(「GMT」)) );' 'cal.setTime(new Date(record.getMillis()));' 它似乎是。 – JamesKingston 2012-10-04 21:15:53

+3

對不起,爲什麼有人需要設置日曆,如果他只需要一個格式化的輸出? – 2013-03-20 16:15:57

相關問題