springboot接收日期字符串參數(shù)與返回日期字符串類型格式化
更新時(shí)間:2024年01月20日 09:53:10 作者:jsq6681993
這篇文章主要介紹了springboot接收日期字符串參數(shù)與返回日期字符串類型格式化,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
接口請(qǐng)求接收日期字符串
方式一
全局注冊(cè)自定義Formatter
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addFormatter(new Formatter<Date>() {
@Override
public Date parse(String date, Locale locale) {
return new Date(Long.parseLong(date));
}
@Override
public String print(Date date, Locale locale) {
return Long.valueOf(date.getTime()).toString();
}
});
}
}方式二
在接口參數(shù)使用@DateTimeFormat注解
// 在參數(shù)上加入該注解
@GetMapping("/testDate")
public void test(@DateTimeFormat(pattern = "yyyy-MM-dd")Date date){
}方式三
參數(shù)映射實(shí)體類屬性上加@DateTimeFormat注解
@Data
public class User{
private String name;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date birthday;
}// 在接收類字段加入該注解
@PostMapping("/testDate")
public void addUser(@RequestBody User user){
}接口請(qǐng)求返回日期字符串格式化
方式一
全局注冊(cè)消息轉(zhuǎn)化器
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//調(diào)用父類的配置
super.configureMessageConverters(converters);
//創(chuàng)建fastJson消息轉(zhuǎn)換器
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
//創(chuàng)建配置類
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig .setDateFormat("yyyy-MM-dd HH:mm:ss");
//保留空的字段
fastJsonConfig .setSerializerFeatures(SerializerFeature.WriteMapNullValue);
// 按需配置,更多參考FastJson文檔
fastConverter .setFastJsonConfig(config);
fastConverter .setDefaultCharset(Charset.forName("UTF-8"));
converters.add(fastConverter );
}
}方式二
返回映射實(shí)體類屬性上加@JsonFormat注解
@Data
public class User{
private String name;
@JsonFormat(pattern="yyyy/MM/dd HH:mm:ss",timezone = "GMT+8")
private Date birthday;
}方式三
配置文件配置
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone=GMT+8總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:
相關(guān)文章
Java實(shí)現(xiàn)Excel導(dǎo)入導(dǎo)出操作詳解
在平常的辦公工作中,導(dǎo)入導(dǎo)出excel數(shù)據(jù)是常見的需求,今天就來看一下通過Java如何來實(shí)現(xiàn)這個(gè)功能,感興趣的朋友可以了解下2022-02-02
如何解決java:找不到符號(hào)符號(hào):類__(使用了lombok的注解)
在使用IntelliJ IDEA開發(fā)Java項(xiàng)目時(shí),可能遇到通過@lombok注解自動(dòng)生成get和set方法不生效的問題,解決這一問題需要幾個(gè)步驟,首先,確認(rèn)Lombok插件已在IDEA中安裝并啟用,其次,確保項(xiàng)目中已添加Lombok的依賴,對(duì)于Maven和Gradle項(xiàng)目2024-10-10
IDEA2020.1構(gòu)建Spring5.2.x源碼的方法
這篇文章主要介紹了IDEA2020.1構(gòu)建Spring5.2.x源碼的方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
Idea工具中使用Mapper對(duì)象有紅線的解決方法
mapper對(duì)象在service層有紅線,項(xiàng)目可以正常使用,想知道為什么會(huì)出現(xiàn)這種情,接下來通過本文給大家介紹下Idea工具中使用Mapper對(duì)象有紅線的問題,需要的朋友可以參考下
2022-09-09 
