【手记】线程安全的日期工具类

ThreadLocal的一个经典案例,将线程不安全的 SimpleDateFormat 类封装成线程安全的:

参考地址1:https://www.cnblogs.com/shuiyj/p/13185060.html

参考地址2:https://blog.csdn.net/YLG_1300710336/article/details/82314328

package stream;

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

/**
 * 线程安全的日期工具类
 * @author zx
 * @date   2020年11月03日
 */
public class CurrentDateUtil {

    /**
     * 默认格式化模式
     */
    private static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss";

    /**
     * 非默认格式化选用格式常量
     */
    public static final String FORMAT_YYYY_MM_DD = "yyyy-MM-dd";



    /**
     * ThreadLocal 持有当前线程的format对象
     */
    private static final ThreadLocal<SimpleDateFormat> THREAD_LOCAL_DATE_FORMAT = ThreadLocal.withInitial(SimpleDateFormat::new);

    /**
     * 设置格式化pattern,自定义格式化格式时使用
     * @param pattern 格式化pattern
     */
    private static void setPattern(String pattern){
        THREAD_LOCAL_DATE_FORMAT.get().applyPattern(pattern);
    }

    /**
     * 使用默认format对象,默认转换为 yyyy-MM-dd HH:mm:ss 格式
     * @param  date 日期参数,不能为空,空则抛出异常
     * @return 转换完成的 yyyy-MM-dd HH:mm:ss 字符串
     */
    public static String format(Date date) throws Exception{
        return format(date, DEFAULT_FORMAT);
    }

    /**
     * 根据传入的pattern设置
     * @param  date    日期参数,不能为空,空则抛出异常
     * @param  pattern 自定义的格式化pattern字符串
     * @return String
     */
    public static String format(Date date, String pattern) throws Exception {
        if(date == null ){
            throw new IllegalArgumentException("param date should not be null ! ");
        }
        if(pattern == null || "".equals(pattern)){
            throw new IllegalArgumentException("param pattern should not be null !");
        }
        setPattern(pattern);
        return THREAD_LOCAL_DATE_FORMAT.get().format(date);
    }

    /**
     * 使用默认的pattern,将字符串转Date类型
     * @param dateStr 日期字符串
     * @return 转换后的日期对象
     */
    public static Date parse(String dateStr) throws Exception{
        return parse(dateStr, DEFAULT_FORMAT);
    }

    /**
     * 使用手动设置的的pattern,将字符串转Date类型
     * @param dateStr 日期字符串
     * @param pattern 自定义的格式化pattern字符串
     * @return 格式化后的日期类型
     */
    public static Date parse(String dateStr, String pattern) throws Exception {
        if(dateStr == null || "".equals(dateStr) ){
            throw new IllegalArgumentException("param dateStr should not be null ! ");
        }
        if(pattern == null || "".equals(pattern)){
            throw new IllegalArgumentException("param pattern should not be null !");
        }
        setPattern(pattern);
        return THREAD_LOCAL_DATE_FORMAT.get().parse(dateStr);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值