获取本地日期,格式化问题,以及解决日期数据类型的转换
今晚在使用Mybatis-plus插入数据库的datetime类型时,遇到了如下报错:
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.util.Date` from String "2021-11-24T17:15:52.941Z": not a valid representation (error: Failed to parse Date value '2021-11-24T17:15:52.941Z': Unparseable date: "2021-11-24T17:15:52.941Z"); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.util.Date` from String "2021-11-24T17:15:52.941Z": not a valid representation (error: Failed to parse Date value '2021-11-24T17:15:52.941Z': Unparseable date: "2021-11-24T17:15:52.941Z")
at [Source: (PushbackInputStream); line: 3, column: 17] (through reference chain: com.suifang.entity.GoodsEvaluateEntity["createTime"])
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:389)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:342)
很明显这是数据类型转换的错误,我们需要考虑将时间'2021-11-24T17:15:52.941Z'转换为当前时区时间并且格式化:
//获取当前时间
//获取当前时间
Date date = new Date();
//日期格式化
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
String now = dateFormat.format(date.getTime());
try {
//最终得到的格式化日期
Date finalDate = dateFormat.parse(now);
goodsEvaluate.setCreateTime(finalDate);
} catch (ParseException e) {
e.printStackTrace();
}