java - 如何在 java 中重用 SimpleDateFormat 类对象以获得不同格式的答案

标签 java date calendar simpledateformat

我们有一个 Calendar 类对象:

Calendar calendar = Calendar.getInstance();

我们有一个 SimpleDateFormat 对象,其格式如下:

SimpleDateFormat dateFormat = new SimpleDateFormat("dd");
String longDate = dateFormat.format(calendar.getTime());

所以我们在 longDate 中获取当前日期。现在我想获取当前年份,但我想重用 dateFormat 对象。有什么办法吗?我知道我可以最初像这样格式化类:

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-yy");

然后从结果字符串中获取结果,但我想重用 dateFormat 对象来获取年份结果。

最佳答案

可以使用applyPattern:

SimpleDateFormat dateFormat = new SimpleDateFormat("dd");
System.out.println(dateFormat.format(new Date()); // 16
dateFormat.applyPattern("dd-yy");
System.out.println(dateFormat.format(new Date()); // 16-18

但是,我个人强烈建议您根本不要使用这些类型,而更喜欢java.time 类型。我还建议不要使用两位数的年份。

关于java - 如何在 java 中重用 SimpleDateFormat 类对象以获得不同格式的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48275922/

相关文章:

java - Android : Converting data from date, 时间选择器从日历到 sql 时间戳和反向。

java - 检查日期是否早于 10 年和新于 20 年

java - 日期加一

javascript - 如何将 vuetify 日历间隔格式更改为 24 小时?

c# - .net 中 ics 文件的解析器

java - 302 链接到其最终 URL 的最快方法是什么?

java - 带有 spring-restdocs 2.0.2.RELEASE 的空指针(带有 Restassured)

Java JButton 大小

calendar - SharePoint 2010:如何将外部列表显示为日历?

java - 将 long[] 更改为 Set。错误消息 : The method addAll in the type Collections is not applicable for the arguments (Set<Long>, 长[])