DateTimeFormatter线程安全的时间格式器

相信大家在项目中会经常获取时间进行操作,平时使用最多的就是SimpleDateFormat时间格式器了,但这个是线程不安全的,就像源码中提到的那样

* <p>
 * Date formats are not synchronized.
 * It is recommended to create separate format instances for each thread.
 * If multiple threads access a format concurrently, it must be synchronized
 * externally.
 *

这就意味着如果要安全使用SimpleDateFormat的话,可以将SimpleDateFormat定义为局部变量,可以通过加一个synchronized(),或者使用ThreadLocal让每个线程都拥有属于自己的本地副本变量达到线程和线程之间的隔离性;阿里巴巴开发手册中推荐的是通过ThreadLocal的方式来避免线程安全问题。

对于这个问题我们可以使用JDK1.8全新的日期和时间API:
获取年月日使用LocalDate、
获取时分秒使用LocalTime、
获取年月日时分秒使用LocalDateTime,
Date如果不格式化,打印出的日期可读性较差,可使用LocalDateTime代替;
直接上例子:

		//可读性较差
		Date date = new Date();
        System.out.println("date类型 = " + date);
        //可读性较好
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println("localDateTime类型 = " + localDateTime);
        System.out.println("----------------------------------------------");

        //线程安全的日期时间格式器
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //当前时间转为字符串
        String currentTime1 = dateTimeFormatter.format(LocalDateTime.now());
        //String currentTime1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now());
        System.out.println("字符串类型时间1 = " + currentTime1);
        //或者
        LocalDateTime now = LocalDateTime.now();
        String currentTime2 = now.format(dateTimeFormatter);
        //String currentTime2 = LocalDateTime.now().format(dateTimeFormatter);
        System.out.println("字符串类型时间2 = " + currentTime2);

        //字符串时间转为LocalDateTime格式
        LocalDateTime parse = LocalDateTime.parse(currentTime1, dateTimeFormatter);
        System.out.println("LocalDateTime类型时间 = " + parse);

结果:
在这里插入图片描述
如有理解偏差之处,还望大家不吝赐教,希望和大家一起共同讨论、同工学习、共同成长!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值