最近在做系統(tǒng)升級,原本的版本為SpringBoot2.1.8RELEASE,升級后版本為SpringBoot2.7.0
升級后原代碼報錯java.time.LocalDateTime cannot be cast to java.sql.Timestamp] with root cause。
經(jīng)檢查,原代碼部分數(shù)據(jù)使用Map接收數(shù)據(jù)庫返回數(shù)據(jù),使用Map.get()取出Object對象后強制轉(zhuǎn)化為了Date類型。
Date CreateTime = (Date)itemMap.get("CreateTime");
升級SpringBoot之前該代碼運行無誤,升級后報錯。原因是MySQL驅(qū)動將數(shù)據(jù)庫中datetime類型識別為了Timestamp類型,而Timestamp無法轉(zhuǎn)化為LocalDateTime。
由于此處的最終需求是將CreateTime轉(zhuǎn)化為String類型,比對Timestamp和LocalDateTime后發(fā)現(xiàn),此處的強制類型轉(zhuǎn)化僅將Timestamp中的‘T’替換為了空格,因此嘗試使用String的replace方法將‘T’替換為空格。
// 2019-12-31T14:00:40 ==> 2019-12-31 14:00:40
CreateTime = CreateTime.replace('T',' ');
但是這種方法在時間為00時會出現(xiàn)bug,例如2019-12-31 14:01:00,在取出字符串時會變?yōu)?strong>2019-12-31 14:01,從而導致位數(shù)缺失。文章來源:http://www.zghlxwxcb.cn/news/detail-404088.html
因此更建議使用LocalDateTime來格式化輸出時間。文章來源地址http://www.zghlxwxcb.cn/news/detail-404088.html
String pattern = "yyyy-MM-dd HH:mm:ss";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
LocalDateTime time = (LocalDateTime)map.get("CreateTime");
String CreateTime = time.format(dateTimeFormatter);
到了這里,關于SpringBoot報錯java.time.LocalDateTime cannot be cast to java.sql.Timestamp] with root cause的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!