线程安全的DateTimeFormatter替换线程不安全的SimpleDateFormat

两者最大的区别是,Java8的DateTimeFormatter是线程安全的,而SimpleDateFormat并不是线程安全。

所以可以用两种方式来替换SimpleDateFormat:

方式一:采用DateUtils工具类的方式

说明:这样就限制了SimpleDateFormat只能在当前线程内共享,这样就避免了多线程导致的线程安全问题。

private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd");
}
};

 //日期转字符串
 public static String format(Date date) {
        return threadLocal.get().format(date);
 }

 //字符串转日期
public static String parse(String str){
    return threadLocal.get.parse(str);
}

方式二:采用JDK8的新特性DateTimeFormatter

说明:DateTimeFormatter是线程安全的,在java.time中

public static void main(String[] args) {
        //DateTimeFormatter 线程安全的日期格式化类
        //日期转换为字符串 ---通过模式字符串来创建DateTimeFormatter格式器,一般用这个
        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy年MM月dd日 hh:mm:ss");
        LocalDateTime now = LocalDateTime.now();
        String format1 = now.format(format);
        System.out.println(format1);
        //直接使用常量创建DateTimeFormatter格式器 ISO_DATE  2018-11-12  / ISO_LOCAL_TIME 14:03:24.266  / ISO_LOCAL_DATE_TIME 2018-11-12T14:03:54.363  / BASIC_ISO_DATE  20181112 等等
        DateTimeFormatter isoDate = DateTimeFormatter.BASIC_ISO_DATE;
        LocalDateTime now2 = LocalDateTime.now();
        String format2 = now.format(isoDate);
        System.out.println(format2);
        //字符串转换为日期
        LocalDateTime now3 = LocalDateTime.now();
        DateTimeFormatter format3 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); //HH24小时制,hh12小时制
        String str = "2014-04-12 01:06:09";
       // LocalDate  不包含时分秒,只有年月日
        LocalDate parse = LocalDate.parse(str, format3);
        System.out.println(parse+" parse");
        //LocalDateTime 年月日时分秒都有,不过要注意,使用localdatetime的时候,格式的时间只能是24小时制,不能用hh,不然会报错
        LocalDateTime parse1 = LocalDateTime.parse(str, format3);
        System.out.println(parse1+" parse1");
        //如果一个字符串没有时分秒,那么是不能直接转换成LocalDateTime的
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDate ld = LocalDate.parse("20180306", dtf);
        //需要指定时分秒,localTime 指定时分秒部分和localDate可以组合使用
        LocalDateTime ldt = LocalDateTime.of(ld, LocalTime.of(12,12,12));
        System.out.println(ldt+" ldt");
        //instant格式化为字符串
  I     Instant now = Instant.now();
        String format = DateTimeFormatter.ofPattern("yyyy:MM:dd HH:mm:ss").format(now);

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值