SimpleDateFormat线程不安全

本文介绍了在使用SimpleDateFormat处理时间格式化时遇到的并发问题及其原因,并提供了使用线程安全的DateTimeFormatter替代的解决方案。

遇到的问题:

项目中设置了静态全局的SimpleDateFormat时间转换的格式,线上在并发使用的时候,出现了时间数据转换混乱的情况

原因:

SimpleDateFormat中,SimpleDateFormat类中定义的Calendar是共享的,并发设值的时候承载的对象可能会被替换,造成转换的数据混乱,如下图所示

解决方法:

试过使用ThreadLocal去构造SimpleDateFormat对象还是没能解决,最终使用了线程安全的DateTimeFormatter进行替换 

DateTimeFormatter用法
时间戳转日期字符串
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); 
LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(System.currentTimeMillis() / 1000L, 0, ZoneOffset.ofHours(8)); 
String format = localDateTime.format(formatter); 
日期时间字符串转时间戳
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); 
LocalDateTime localDateTime = LocalDateTime.parse("2020-09-03 10:20:11", formatter); 
long l = localDateTime.toInstant(ZoneOffset.ofHours(8)).toEpochMilli(); 
日期字符串转时间戳 
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd"); 
LocalDate localDate = LocalDate.parse("2020/09/03", formatter); 
long l = localDate.atStartOfDay(ZoneOffset.ofHours(8)).toInstant().toEpochMilli();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值