Date Conversion with ThreadLocal

后端 未结 2 1461
无人及你
无人及你 2021-01-05 00:44

I have a requirement to convert incoming date string format \"20130212\" (YYYYMMDD) to 12/02/2013 (DD/MM/YYYY)

using ThreadLocal. I know a way to do th

2条回答
  •  半阙折子戏
    2021-01-05 01:37

    ThreadLocal in Java is a way to achieve thread-safety apart from writing immutable classes. Since SimpleDateFormat is not thread safe, you can use a ThreadLocal to make it thread safe.

    class DateFormatter{
    
        private static ThreadLocal outDateFormatHolder = new ThreadLocal() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("MM/dd/yyyy");
        }
    };
    
    private static ThreadLocal inDateFormatHolder = new ThreadLocal() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyyMMdd");
        }
    };
    
    public static String formatDate(String date) throws ParseException { 
        return outDateFormatHolder.get().format(
                inDateFormatHolder.get().parse(date));
    }        
    }
    

提交回复
热议问题