Java日期格式化-线程安全

来源:互联网 发布:剑灵极品龙女数据 编辑:程序博客网 时间:2024/06/05 16:12
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package my.util.DateTimeTools;


import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 *
 * @author Administrator
 */
public class SafeDateFormat {


    final static Map<String, ThreadLocal<DateFormat>> threadLocalPool = new HashMap<>();
    final static ThreadLocal<DateFormat> DefaultThreadLocal = new ThreadLocal<DateFormat>() {
        @Override
        protected synchronized DateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };


    static {
        threadLocalPool.put("yyyy-MM-dd HH:mm:ss", DefaultThreadLocal);
    }


    public static Date parse(String dateStr) throws ParseException {


        return DefaultThreadLocal.get().parse(dateStr);


    }


    public static Date parse(final String format, String dateStr) throws ParseException {
        ThreadLocal<DateFormat> threadLocal = threadLocalPool.get(format);
        if (threadLocal == null) {
            threadLocal = new ThreadLocal<DateFormat>() {
                @Override
                protected synchronized DateFormat initialValue() {
                    return new SimpleDateFormat(format);
                }
            };
            threadLocalPool.put(format, threadLocal);
        }
        return threadLocal.get().parse(dateStr);


    }


    public static String format(Date date) {
        return DefaultThreadLocal.get().format(date);
    }


    public static String format(final String format, Date date) {
        ThreadLocal<DateFormat> threadLocal = threadLocalPool.get(format);
        if (threadLocal == null) {
            threadLocal = new ThreadLocal<DateFormat>() {
                @Override
                protected synchronized DateFormat initialValue() {
                    return new SimpleDateFormat(format);
                }
            };
            threadLocalPool.put(format, threadLocal);
        }
        return threadLocal.get().format(date);
    }
}
原创粉丝点击