如何将 SimpleDateFormat 与日历一起使用?

新手上路,请多包涵

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

原文由 Denys S. 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 369
2 个回答

尝试这个:

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

原文由 janhink 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

原文由 JamesKingston 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题