最近在做系统升级,原本的版本为SpringBoot2.1.8RELEASE,升级后版本为SpringBoot2.7.0

升级后原代码报错java.time.LocalDateTime cannot be cast to java.sql.Timestamp] with root cause。

经检查,原代码部分数据使用Map接收数据库返回数据,使用Map.get()取出Object对象后强制转化为了Date类型。

Date CreateTime = (Date)itemMap.get("CreateTime");

升级SpringBoot之前该代码运行无误,升级后报错。原因是MySQL驱动将数据库中datetime类型识别为了Timestamp类型,而Timestamp无法转化为LocalDateTime。

由于此处的最终需求是将CreateTime转化为String类型,比对Timestamp和LocalDateTime后发现,此处的强制类型转化仅将Timestamp中的‘T’替换为了空格,因此尝试使用String的replace方法将‘T’替换为空格。

// 2019-12-31T14:00:40 ==> 2019-12-31 14:00:40
CreateTime = CreateTime.replace('T',' ');

但是这种方法在时间为00时会出现bug,例如2019-12-31 14:01:00,在取出字符串时会变为2019-12-31 14:01,从而导致位数缺失。

因此更建议使用LocalDateTime来格式化输出时间。

String pattern = "yyyy-MM-dd HH:mm:ss";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
LocalDateTime time = (LocalDateTime)map.get("CreateTime");
String CreateTime = time.format(dateTimeFormatter);
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐