注解@JsonFormat主要是后台到前台的时间格式的转换

@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")

注解@DataFormAT主要是前后到后台的时间格式的转换

@DateTimeFormat(pattern ="yyyy-MM-dd HH:mm:ss")

spring mvc是通过jackson来序列化/反序列化json字符串的;

jackson支持的日期格式:

"yyyy-MM-dd'T'HH:mm:ss.SSSZ";
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
"yyyy-MM-dd";
"EEE, dd MMM yyyy HH:mm:ss zzz";
long类型的时间戳;

数据库的日期格式为yyyy-MM-dd HH:mm:ss

解决方案:

在spring boot配置文件中加上如下代码:

spring.mvc.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8

@Slf4j
@ControllerAdvice
public class GlobalExceptionResolver extends DefaultHandlerExceptionResolver {

@ExceptionHandler(value = Exception.class)
public void defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) throws Exception {
if (e!=null){
log.info(e.getMessage());
Map<String, Object> result = new HashMap<>();
result.put("code", 777);
result.put("msg", "请求数据格式错误");
String jsonStr = JSONUtils.toJSONString(result);
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter wirte = response.getWriter();
wirte.print(jsonStr);
wirte.flush();
wirte.close();
}
}
}