如何在日历中使用SimpleDateFormat?

Den*_* S. 67 java formatting calendar date simpledateformat

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

jan*_*ink 95

试试这个:

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

  • @kamaci在JamesKingston的回答中看到了评论.仅当您的日历对象基于与系统默认时区不同的时区并且您希望它在该日历的时区中打印时才有意义.如果不设置时区,则将使用默认系统时区.如果这与日历的时区相同,则设置时区没有区别.请注意,JamesKingston的答案也有效 - 告诉dateFormat使用哪个日历意味着它将知道使用日历的时区. (2认同)

Jam*_*ton 34

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()));
Run Code Online (Sandbox Code Playgroud)

  • 对不起,为什么有人需要设置日历,如果他只需要格式化的输出? (3认同)
  • 对于这种情况并不重要,但如果你想做的事情如下:`cal.setTimeZone(TimeZone.getTimeZone("GMT"));``cal.setTime(new Date(record.getMillis()));`好像是. (2认同)