Spring?@DateTimeFormat日期格式化時(shí)注解場(chǎng)景分析
總結(jié)寫(xiě)前面
關(guān)于它 @DateTimeFormat:
- 可以接收解析前端傳入字符時(shí)間數(shù)據(jù);
- 不能格式化接收的字符時(shí)間類(lèi)型數(shù)據(jù),需要的轉(zhuǎn)換格式得配置;
- 入?yún)⒏袷奖仨毰c后端注解格式保持一致,否則會(huì)報(bào)錯(cuò);
為什么用
場(chǎng)景:跟前端交互時(shí),接收字符類(lèi)型的時(shí)間值,就需要使用 @DateTimeFormat 注解來(lái)解析,否則就會(huì)報(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;
}請(qǐng)求示例結(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]]
怎么用
場(chǎng)景一
接收非 JSON 格式請(qǐng)求參數(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;
}請(qǐng)求示例結(jié)果:
- 請(qǐng)求:POST
- 數(shù)據(jù)格式:form-data

從結(jié)果可以看出,@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") 可以保證接收解析前端傳入的字符時(shí)間參數(shù),但是并不能完成時(shí)間格式化操作,如果需要獲取想要的時(shí)間格式,是需要自己手動(dòng)轉(zhuǎn)換的。
場(chǎng)景二
接收 JSON 格式請(qǐng)求數(shù)據(jù),與場(chǎng)景一的區(qū)別是請(qǐng)求的數(shù)據(jù)格式:
- 場(chǎng)景一:form-data
- 場(chǎng)景二: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;
}請(qǐng)求示例結(jié)果:
- 請(qǐng)求:POST
- 數(shù)據(jù)格式:JSON

從結(jié)果可以看出,返回?cái)?shù)據(jù) nowTime 是空的,因?yàn)檫@里的Controller層沒(méi)有使用 @RequestBody 去接收 JSON 格式的數(shù)據(jù),而 Spring 默認(rèn)的轉(zhuǎn)換器類(lèi)型是不包含 JSON 的(有興趣的可以看下 org.springframework.core.convert.support 包,這里面包含Spring支持的默認(rèn)轉(zhuǎn)換器)。
場(chǎng)景三
場(chǎng)景三跟場(chǎng)景二的區(qū)別就是,在 Controller 層方法入?yún)⑴浜鲜褂?@RequestBody 去接收 JSON 格式,使用該注解會(huì)自動(dòng)調(diào)用對(duì)應(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;
}請(qǐng)求示例結(jié)果:
- 請(qǐng)求:POST
- 數(shù)據(jù)格式:JSON

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

大概意思就是說(shuō),Spring 框架在嘗試轉(zhuǎn)換參數(shù)的過(guò)程中,沒(méi)有找到合適接收格式導(dǎo)致轉(zhuǎn)換失敗。(注意!注意!注意!講三遍,所以前端入?yún)⒏袷奖仨毰c后端約定格式保持一致,否則會(huì)報(bào)錯(cuò))。
場(chǎng)景四
場(chǎng)景四的目的是為了解決場(chǎng)景一中時(shí)間格式化的問(wèn)題。
關(guān)于 @JsonFormat 注解,可以看看我的另一篇blog中有做分享,感興趣的大佬可以去看看,附上傳送門(mén):@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;
}請(qǐng)求示例結(jié)果:
- 請(qǐng)求:POST
- 數(shù)據(jù)格式:form-data

場(chǎng)景五
方式一
針對(duì)場(chǎng)景四的數(shù)據(jù)請(qǐng)求格式是 form-data,場(chǎng)景五來(lái)說(shuō)明 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;
}請(qǐng)求示例結(jié)果:
- 請(qǐng)求:POST
- 數(shù)據(jù)格式:JSON

方式二
可以繼承 Spring 提供的org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer 來(lái)進(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";
// 針對(duì)于Date類(lèi)型,文本格式化
jacksonObjectMapperBuilder.simpleDateFormat(dateFormat);
// 針對(duì)于JDK新時(shí)間類(lèi)。序列化時(shí)帶有T的問(wèn)題,自定義格式化字符串
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失效問(wèn)題
*/
@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);
}
}
}請(qǐng)求示例結(jié)果:
- 請(qǐng)求:POST
- 數(shù)據(jù)格式:JSON

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

