Formatting MMyyyy to MMyy The following is my sample code:

String month = "09";

String year = "2014";

String monthYear = "092014";


The monthYear format is MMyyyy, I wish to format it to become MMyy. Thus, I am doing it as follows:

Method 1:

final SimpleDateFormat oriMonthYear = new SimpleDateFormat( "MMyyyy" );
final SimpleDateFormat changeMonthYear = new SimpleDateFormat( "MMyy" );

String newMonthYear = changeMonthYear.format( oriMonthYear.parse( month + year) );


This give me correct output, but I am not sure am I doing it by stupid way or not. I believe it should be another best practice and smart to way to do it.
Use Java's THreadLocal type to wrap your SimpleDateFormat objects.

ThreadLocal&lt;SimpleDateFormat&gt; oriFormatHolder = new ThreadLocal&lt;SimpleDateFormat&gt;() {

    @Override
    protected SimpleDateFormat initialValue() {
        return new SimpleDateFormat("MMyyyy");
    }
};


final SimpleDateFormat oriMonthYear = oriFormatHolder.get();


The reason for this is because SimpleDateFormat is not thread safe.


  Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.


Read more here

I actually ran into this problem.  In a multi threaded env we were sharing a SimpleDateFormat object across many threads and started getting bad results.  By wrapping it with ThreadLocal the problem went away.