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ù)映射實(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 );
}
}方式二
返回映射實(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é)
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot中的@EnableConfigurationProperties注解原理及用法
在SpringBoot中,@EnableConfigurationProperties注解是一個非常有用的注解,它可以用于啟用對特定配置類的支持,在本文中,我們將深入探討@EnableConfigurationProperties注解,包括它的原理和如何使用,需要的朋友可以參考下2023-06-06
mybatis中映射文件include標(biāo)簽的應(yīng)用
這篇文章主要介紹了mybatis中映射文件include標(biāo)簽的應(yīng)用,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11
十大常見Java String問題_動力節(jié)點(diǎn)Java學(xué)院整理
本文介紹Java中關(guān)于String最常見的10個問題,需要的朋友參考下吧2017-04-04
Java進(jìn)階之FileUpload完成上傳的實(shí)例
這篇文章主要介紹了 Java進(jìn)階之FileUpload完成上傳的實(shí)例的相關(guān)資料,希望通過本文能幫助到大家,需要的朋友可以參考下2017-09-09
IDEA中g(shù)it對于指定文件進(jìn)行版本控制的全過程
用戶在IDEA中遇到默認(rèn)提交所有修改的問題,通過配置.gitignore和.git/info/exclude忽略特定文件,并利用vcs.xml指定版本控制范圍,實(shí)現(xiàn)精準(zhǔn)版本管理,本文通過圖文給大家介紹了IDEA中g(shù)it對于指定文件進(jìn)行版本控制的全過程,需要的朋友可以參考下2025-05-05
idea中提示Class 'xxx' is never us
這篇文章主要介紹了idea中提示Class 'xxx' is never used的解決方案,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01

