Java 如何将SimpleDataFormat与日历一起使用?

Java 如何将SimpleDataFormat与日历一起使用?,java,date,calendar,formatting,simpledateformat,Java,Date,Calendar,Formatting,Simpledateformat,我有GregorianCalendar实例,需要使用SimpleDataFormat(或者可以与calendar一起使用,但提供必需的#fromat()功能)来获得所需的输出。请建议解决方案,就像永久解决方案一样好 Calendar.getTime()返回一个可以与SimpleDataFormat一起使用的日期。只需调用Calendar.getTime(),并将生成的Date对象传递给format方法。尝试以下操作: Calendar cal = new GregorianCalendar();

我有GregorianCalendar实例,需要使用SimpleDataFormat(或者可以与calendar一起使用,但提供必需的#fromat()功能)来获得所需的输出。请建议解决方案,就像永久解决方案一样好

Calendar.getTime()返回一个可以与SimpleDataFormat一起使用的日期。

只需调用
Calendar.getTime()
,并将生成的
Date
对象传递给
format
方法。

尝试以下操作:

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

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

+因为答案是最完整的。如果没有此方法调用,将使用默认日历进行格式化。(然而,问题并没有真正指定应该使用哪个日历进行格式化。)对于这种情况,这并不重要,但如果您想执行以下操作:
cal.setTimeZone(TimeZone.getTimeZone(“GMT”)
cal.setTime(新日期(record.getMillis())似乎是。请问,如果某人只需要格式化输出,为什么需要设置日历?为了强调JamesKingston之前的评论,eQui的回答(即不使用dateFormat.setCalendar)将产生错误的输出,如果“cal”的时区不是系统默认时区。要回答@denys-s,这不仅仅是一个格式问题,也是一个正确性问题。我应该澄清一下,“正确性”的意思是,如果没有setCalendar,它将在显示之前将日历转换为系统默认时区,这可能不是您想要的(尤其是如果您没有在格式字符串中列出时区!). 例如,即使使用代码将日历显式设置为2014-05-08,也可能显示为2014-05-07或2014-05-09,具体取决于时区偏移量。添加了JamesKingston答案中缺少的步骤。谢谢不加时区会有什么影响?@kamaci在詹姆斯金斯顿的回答中看到了评论。只有当您有一个基于不同于系统默认时区的时区的日历对象,并且希望它在该日历的时区中打印时,才有意义。如果不设置时区,它将使用默认的系统时区。如果这与日历的时区相同,则设置时区没有区别。请注意,JamesKingston的回答同样有效——告诉dateFormat使用哪个日历意味着它将知道如何使用日历的时区。