使用ThreadLocal进行日期转换
我需要将传入日期字符串格式“ 20130212”(YYYYMMDD)转换为12/02/2013(DD / MM / YYYY)
使用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));
回答:
Java中的ThreadLocal除了编写不可变的类外,还是一种实现线程安全的方法。由于SimpleDateFormat不是线程安全的,因此可以使用ThreadLocal使其成为线程安全的。
class DateFormatter{    private static ThreadLocal<SimpleDateFormat> outDateFormatHolder = new ThreadLocal<SimpleDateFormat>() {
    @Override
    protected SimpleDateFormat initialValue() {
        return new SimpleDateFormat("MM/dd/yyyy");
    }
};
private static ThreadLocal<SimpleDateFormat> inDateFormatHolder = new ThreadLocal<SimpleDateFormat>() {
    @Override
    protected SimpleDateFormat initialValue() {
        return new SimpleDateFormat("yyyyMMdd");
    }
};
public static String formatDate(String date) throws ParseException { 
    return outDateFormatHolder.get().format(
            inDateFormatHolder.get().parse(date));
}        
}
以上是 使用ThreadLocal进行日期转换 的全部内容, 来源链接: utcz.com/qa/418834.html








