Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 650
Imad062 Avatar asked Jan 16 '18 07:01

Imad062


People also ask

Can SimpleDateFormat be reused?

The conclusion is that we must reuse as much as possible the instances of SimpleDateFormat. At a first look this can be done by making the SimpleDateFormat instance static, which means we only need to create one instance.

What can I use instead of SimpleDateFormat?

DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.

How do I change date format in SimpleDateFormat?

String date_s = " 2011-01-18 00:00:00.0"; SimpleDateFormat dt = new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss"); Date date = dt. parse(date_s); SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd"); System. out. println(dt1.

How do I change the date format in Java Util?

// Setting the pattern SimpleDateFormat sm = new SimpleDateFormat("mm-dd-yyyy"); // myDate is the java. util. Date in yyyy-mm-dd format // Converting it into String using formatter String strDate = sm. format(myDate); //Converting the String back to java.


1 Answers

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.

like image 89
Jon Skeet Avatar answered Sep 27 '22 16:09

Jon Skeet