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.
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.
DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.
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.
// 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With