springboot接收日期字符串參數(shù)與返回日期字符串類型格式化
更新時間:2024年01月20日 09:53:10 作者:jsq6681993
這篇文章主要介紹了springboot接收日期字符串參數(shù)與返回日期字符串類型格式化,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
接口請求接收日期字符串
方式一
全局注冊自定義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ù)映射實體類屬性上加@DateTimeFormat注解
@Data
public class User{
private String name;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date birthday;
}// 在接收類字段加入該注解
@PostMapping("/testDate")
public void addUser(@RequestBody User user){
}接口請求返回日期字符串格式化
方式一
全局注冊消息轉(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 );
}
}方式二
返回映射實體類屬性上加@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é)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:
相關文章
如何解決java:找不到符號符號:類__(使用了lombok的注解)
在使用IntelliJ IDEA開發(fā)Java項目時,可能遇到通過@lombok注解自動生成get和set方法不生效的問題,解決這一問題需要幾個步驟,首先,確認Lombok插件已在IDEA中安裝并啟用,其次,確保項目中已添加Lombok的依賴,對于Maven和Gradle項目2024-10-10

