Spring?@DateTimeFormat日期格式化時(shí)注解場景分析
總結(jié)寫前面
關(guān)于它 @DateTimeFormat:
- 可以接收解析前端傳入字符時(shí)間數(shù)據(jù);
- 不能格式化接收的字符時(shí)間類型數(shù)據(jù),需要的轉(zhuǎn)換格式得配置;
- 入?yún)⒏袷奖仨毰c后端注解格式保持一致,否則會報(bào)錯(cuò);
為什么用
場景:跟前端交互時(shí),接收字符類型的時(shí)間值,就需要使用 @DateTimeFormat 注解來解析,否則就會報(bào)錯(cuò);
@RestController
@RequestMapping("/demo")
public class DemoTestController {
@PostMapping("/testOne")
public DemoTest testOne(DemoTest demoTest){
return demoTest;
}
}
@Data
public class DemoTest {
private Date nowTime;
}請求示例結(jié)果:
Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors<EOL>Field error in object 'demoTest' on field 'nowTime': rejected value [2022-11-20 16:42:26,2022-11-20 16:42:01]; codes [typeMismatch.demoTest.nowTime,typeMismatch.nowTime,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [demoTest.nowTime,nowTime]; arguments []; default message [nowTime]]; default message [Failed to convert property value of type 'java.lang.String[]' to required type 'java.util.Date' for property 'nowTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2022-11-20 16:42:26'; nested exception is java.lang.IllegalArgumentException]]
怎么用
場景一
接收非 JSON 格式請求參數(shù)。
@RestController
@RequestMapping("/demo")
public class DemoTestController {
@PostMapping("/testOne")
public DemoTest testOne(DemoTest demoTest){
return demoTest;
}
}
@Data
public class DemoTest {
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date nowTime;
}請求示例結(jié)果:
- 請求:POST
- 數(shù)據(jù)格式:form-data

從結(jié)果可以看出,@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") 可以保證接收解析前端傳入的字符時(shí)間參數(shù),但是并不能完成時(shí)間格式化操作,如果需要獲取想要的時(shí)間格式,是需要自己手動轉(zhuǎn)換的。
場景二
接收 JSON 格式請求數(shù)據(jù),與場景一的區(qū)別是請求的數(shù)據(jù)格式:
- 場景一:form-data
- 場景二:JSON
@RestController
@RequestMapping("/demo")
public class DemoTestController {
@PostMapping("/testTwo")
public DemoTest testTwo(DemoTest demoTest){
return demoTest;
}
}
@Data
public class DemoTest {
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date nowTime;
}請求示例結(jié)果:
- 請求:POST
- 數(shù)據(jù)格式:JSON

從結(jié)果可以看出,返回?cái)?shù)據(jù) nowTime 是空的,因?yàn)檫@里的Controller層沒有使用 @RequestBody 去接收 JSON 格式的數(shù)據(jù),而 Spring 默認(rèn)的轉(zhuǎn)換器類型是不包含 JSON 的(有興趣的可以看下 org.springframework.core.convert.support 包,這里面包含Spring支持的默認(rèn)轉(zhuǎn)換器)。
場景三
場景三跟場景二的區(qū)別就是,在 Controller 層方法入?yún)⑴浜鲜褂?@RequestBody 去接收 JSON 格式,使用該注解會自動調(diào)用對應(yīng)的JSON轉(zhuǎn)換器。
@RestController
@RequestMapping("/demo")
public class DemoTestController {
@PostMapping("/testThree")
public DemoTest testThree(@RequestBody DemoTest demoTest){
return demoTest;
}
}
@Data
public class DemoTest {
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date nowTime;
}請求示例結(jié)果:
- 請求:POST
- 數(shù)據(jù)格式:JSON

這里可以看到,請求報(bào)錯(cuò)400,導(dǎo)致400的原因比較多,這里只說明一下場景三,場景三中使用 @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") 注解格式與請求入?yún)⒏袷讲灰恢拢詴?dǎo)致請求報(bào)錯(cuò);

大概意思就是說,Spring 框架在嘗試轉(zhuǎn)換參數(shù)的過程中,沒有找到合適接收格式導(dǎo)致轉(zhuǎn)換失敗。(注意!注意!注意!講三遍,所以前端入?yún)⒏袷奖仨毰c后端約定格式保持一致,否則會報(bào)錯(cuò))。
場景四
場景四的目的是為了解決場景一中時(shí)間格式化的問題。
關(guān)于 @JsonFormat 注解,可以看看我的另一篇blog中有做分享,感興趣的大佬可以去看看,附上傳送門:@JsonFormat 和 @DateTimeFormat 時(shí)間格式化注解詳解(不看血虧)
@RestController
@RequestMapping("/demo")
public class DemoTestController {
@PostMapping("/testThree")
public DemoTest testThree(@RequestBody DemoTest demoTest){
return demoTest;
}
}
@Data
public class DemoTest {
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date nowTime;
}請求示例結(jié)果:
- 請求:POST
- 數(shù)據(jù)格式:form-data

場景五
方式一
針對場景四的數(shù)據(jù)請求格式是 form-data,場景五來說明 JSON 同樣適用。
@RestController
@RequestMapping("/demo")
public class DemoTestController {
@PostMapping("/testThree")
public DemoTest testThree(@RequestBody DemoTest demoTest){
return demoTest;
}
}
@Data
public class DemoTest {
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date nowTime;
}請求示例結(jié)果:
- 請求:POST
- 數(shù)據(jù)格式:JSON

方式二
可以繼承 Spring 提供的org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer 來進(jìn)行全局配置。
@RestController
@RequestMapping("/demo")
public class DemoTestController {
@PostMapping("/testThree")
public DemoTest testThree(@RequestBody DemoTest demoTest){
return demoTest;
}
}
@Data
public class DemoTest {
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date nowTime;
}
@Configuration
public class CustomsDateConvert implements Jackson2ObjectMapperBuilderCustomizer {
@Override
public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
String dateFormat = "yyyy-MM-dd HH";
// 針對于Date類型,文本格式化
jacksonObjectMapperBuilder.simpleDateFormat(dateFormat);
// 針對于JDK新時(shí)間類。序列化時(shí)帶有T的問題,自定義格式化字符串
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateFormat)));
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(dateFormat)));
jacksonObjectMapperBuilder.modules(javaTimeModule);
}
}
/**
* 解決Jackson2ObjectMapperBuilderCustomizer失效問題
*/
@Configuration
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public class ConvertConfiguration implements WebMvcConfigurer {
@Autowired(required = false)
private MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter;
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.removeIf(converter -> converter instanceof MappingJackson2HttpMessageConverter);
if (Objects.isNull(mappingJackson2HttpMessageConverter)) {
converters.add(0, new MappingJackson2HttpMessageConverter());
} else {
converters.add(0, mappingJackson2HttpMessageConverter);
}
}
}請求示例結(jié)果:
- 請求:POST
- 數(shù)據(jù)格式:JSON

到此這篇關(guān)于Spring @DateTimeFormat日期格式化時(shí)注解場景分析的文章就介紹到這了,更多相關(guān)Spring @DateTimeFormat日期格式化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java使用自定義注解實(shí)現(xiàn)函數(shù)測試功能示例
這篇文章主要介紹了Java使用自定義注解實(shí)現(xiàn)函數(shù)測試功能,結(jié)合實(shí)例形式分析了java自定義注解在函數(shù)測試過程中相關(guān)功能、原理與使用技巧,需要的朋友可以參考下2019-10-10
java 通過cmd 調(diào)用命令啟動tomcat的操作
這篇文章主要介紹了java 通過cmd 調(diào)用命令啟動tomcat的操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11
java-流的使用完結(jié)與異常處理機(jī)制(詳解)
下面小編就為大家?guī)硪黄猨ava-流的使用完結(jié)與異常處理機(jī)制(詳解)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-09-09
使用@DS輕松解決動態(tài)數(shù)據(jù)源的問題
這篇文章主要介紹了使用@DS輕松解決動態(tài)數(shù)據(jù)源的問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05
Java數(shù)據(jù)庫操作庫DButils類的使用方法與實(shí)例詳解
這篇文章主要介紹了JDBC數(shù)據(jù)庫操作庫DButils類的使用方法詳解,需要的朋友可以參考下2020-02-02

