相信大家在项目中会经常获取时间进行操作,平时使用最多的就是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);
结果:
如有理解偏差之处,还望大家不吝赐教,希望和大家一起共同讨论、同工学习、共同成长!