首页 > 代码库 > 多线程下 SimpleDateFormat

多线程下 SimpleDateFormat

package com.shob.tt.single;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class StringUtil {

	/**
	 * SimpleDateFormat在多线程环境下容易造成数据转换及处理数据的不准确
	 * 处理方式:创建多个SimpleDateFormat
	 * @param formatPattern
	 * @param dateString
	 * @return
	 * @throws ParseException
	 */
	public static Date parse(String formatPattern,String dateString) throws ParseException{
		return new SimpleDateFormat(formatPattern).parse(dateString);
	}
	
	public static String format(String formatPattern,Date date) throws ParseException{
		return new SimpleDateFormat(formatPattern).format(date);
	}
	
	private static ThreadLocal<SimpleDateFormat> tl = new ThreadLocal<SimpleDateFormat>();
	/**
	 * ThreadLocal 类能使线程绑定到指定对象
	 * @param formatPattern
	 * @return
	 */
	public static SimpleDateFormat getSimpleDateFormat(String formatPattern){
		SimpleDateFormat sdf = null;
		sdf = tl.get();
		if(null == sdf){
			sdf = new SimpleDateFormat(formatPattern);
			tl.set(sdf);
		}
		return sdf;
	}
}

  

多线程下 SimpleDateFormat