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.
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.
See more on this question at Stackoverflow