遇到的问题:
项目中设置了静态全局的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();
本文介绍了在使用SimpleDateFormat处理时间格式化时遇到的并发问题及其原因,并提供了使用线程安全的DateTimeFormatter替代的解决方案。
4408

被折叠的 条评论
为什么被折叠?



