1、在javaweb項目中,我們會接受前臺傳入的date類型
在接受的過程中,經常會遇到日期轉換異常,前臺傳的格式可能是2019-04-03 00:00:00或者2019-09-19T16:00:00.000Z,後臺後者如果用Date對象來接受可能會出現問題,在你的controller中添加如下配置可以解決此問題,
@InitBinder
public void initBinder(ServletRequestDataBinder binder) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
}
此處"2019-09-19T16:00:00.000Z"此類格式可能還會有問題,可以嘗試前端修改傳參格式
2、我們也可以控制調用別人接口時傳出的格式,
在application.properties文件中添加如下配置
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
spring.jackson.parser.allow-unquoted-control-chars=true
spring.jackson.parser.allow-single-quotes=true
spring.jackson.parser.allow-backslash-escaping-any-character=true
注: 1中是接受時候接收方對於時間格式的轉換,2中是傳給被調用接口之前傳出的格式控制