我需要将传入日期字符串格式“20130212”(YYYYMMDD) 转换为 12/02/2013 (DD/MM/YYYY)
using ThreadLocal
。我知道一种无需ThreadLocal
。谁能帮我?
转换无ThreadLocal
:
final SimpleDateFormat format2 = new SimpleDateFormat("MM/dd/yyyy");
final SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMdd");
final Date date = format1.parse(tradeDate);
final Date formattedDate = format2.parse(format2.format(date));
这背后的想法是 SimpleDateFormat 不是线程安全的,因此在多线程应用程序中,您无法在多个线程之间共享 SimpleDateFormat 的实例。但由于创建 SimpleDateFormat 是一项昂贵的操作,我们可以使用 ThreadLocal 作为解决方法
static ThreadLocal<SimpleDateFormat> format1 = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd");
}
};
public String formatDate(Date date) {
return format1.get().format(date);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)