如何在日历中使用SimpleDateFormat?

时间:2011-04-11 13:11:51

标签: java date calendar formatting simpledateformat

我有GregorianCalendar实例,需要使用SimpleDateFormat(或者可以用于日历,但提供所需的#fromat()功能)以获得所需的输出。请建议解决方案和永久解决方案一样好。

4 个答案:

答案 0 :(得分:92)

试试这个:

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

答案 1 :(得分:33)

eQui的答案缺少一步

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

答案 2 :(得分:3)

Calendar.getTime()返回一个可以与SimpleDateFormat一起使用的Date。

答案 3 :(得分:3)

只需致电calendar.getTime(),然后将生成的Date对象传递给format方法。