2011-04-11 49 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

相关问题