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

How to reuse a SimpleDateFormat class object in java to get different formatted answer

我们有一个 Calendar class 对象:

Calendar calendar = Calendar.getInstance();

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

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

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

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 类型。我还建议不要使用两位数的年份。

既然您已经有了日历对象,为什么不直接调用它的 get 方法

int day = calendar.get(Calendar.DAY_OF_MONTH);