How to reuse object of class SimpleDateFormat in java to get formatted response

We have a class object Calendar:

Calendar calendar = Calendar.getInstance();

And we have an object SimpleDateFormatthat is formatted as follows:

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 object dateFormat. Is there any way to do this? I know that I can format the class initially :

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

and then get the results from the summary row, but I want to reuse the object dateFormatto get the results of the year.

+6
source share
2 answers

, 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. 2- .

+20

Calendar, get method

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

All Articles