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

We have a Calendar class object:

Calendar calendar = Calendar.getInstance();

And we have a SimpleDateFormat object which is formatted like below:

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

So we get the current date in longDate. Now I want to get the current year, but I want to reuse the dateFormat object. Is there any way to do it? I know I can initially format the class like:

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

and then get the results from the resultant string, but I want to reuse the dateFormat object to get the year results.

Jon Skeet
people
quotationmark

Well you can use 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

However, I would personally strongly recommend that you not use these types at all, preferring the java.time types. I'd also recommend against using 2-digit years.

people

See more on this question at Stackoverflow