DateFormat df = new SimpleDateFormat( "MM/dd/yy");
return df.format( new Date());
}
public String formatFirstOfJanyary1970() {
DateFormat df = new SimpleDateFormat( "MM/dd/yy");
return df.format( new Date( 0));
}
推荐Java Code Geeks上的两篇文章:
——误用ThreadLocal可能会导致OutOfMemoryError。
Instead of grinding my teeth, I decided to open up the topic by publishing two articles, first of which you are currently reading. In the post I explain the motivation behind ThreadLocal usage. In the second post currently in progress I will open up the ThreadLocal bonnet and look at the implementation.
【正例】为不同地区的用户显示不同的日期格式
Let us start with an imaginary scenario in which ThreadLocal usage is indeed reasonable. For this, say hello to our hypothetical developer, named Tim. Tim is developing a webapp, in which there is a lot of localized content. For example a user from California would expect to be greeted with date formatted using a familiar MM/dd/yy pattern, one from Estonia on the other hand would like to see a date formatted according to dd.MM.yyyy. So Tim starts writing code like this:
改进:将DateFormat提取出来作为实例变量。
After a while, Tim finds this to be boring and against good practices – the application code is polluted with such initializations. So he makes a seemingly reasonable move by extracting the DateFormat to an instance variable. After making the move, his code now looks like the following: