在SpringMVC中通過@RequestParam接收jdk8的LocalDateTime時間類型的時候
前端通過傳入
后台接收方式
會出現如下異常:
org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDateTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam java.time.LocalDateTime] for value '2018-11-11 12:12:12'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2018-11-11 12:12:12]
解決方式:
是通過@DateTimeFormat注解,去解析前端傳入的時間格式字符串然后轉化成LocaDateTime的時間類型
那么同時可以說一下
@JsonFormat:他和@DateTimeFormat正好對應關系,如果我們從DB中取得時間類型數據,想傳回前端,並且規定格式,那么就可以使用@JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")
pattern:是你需要轉換的時間日期的格式
timezone:是時間設置為東八區,避免時間在轉換中有誤差
提示:@JsonFormat注解可以在屬性的上方,同樣可以在屬性對應的get方法上,兩種方式沒有區別