springboot接收日期字符串参数与返回日期字符串类型格式化
更新时间:2024年01月20日 09:53:10 作者:jsq6681993
这篇文章主要介绍了springboot接收日期字符串参数与返回日期字符串类型格式化,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
接口请求接收日期字符串
方式一
全局注册自定义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(); } }); } }
方式二
在接口参数使用@DateTimeFormat注解
// 在参数上加入该注解 @GetMapping("/testDate") public void test(@DateTimeFormat(pattern = "yyyy-MM-dd")Date date){ }
方式三
参数映射实体类属性上加@DateTimeFormat注解
@Data public class User{ private String name; @DateTimeFormat(pattern = "yyyy-MM-dd") private Date birthday; }
// 在接收类字段加入该注解 @PostMapping("/testDate") public void addUser(@RequestBody User user){ }
接口请求返回日期字符串格式化
方式一
全局注册消息转化器
@Configuration public class MyWebMvcConfigurer implements WebMvcConfigurer { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { //调用父类的配置 super.configureMessageConverters(converters); //创建fastJson消息转换器 FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); //创建配置类 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
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
相关文章
详细介绍Java关键字throw throws Throwable的用法与区别
这篇文章主要介绍了java中throws与throw及Throwable的用法和区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2022-04-04SpringBoot2.1.3修改tomcat参数支持请求特殊符号问题
最近遇到一个问题,比如GET请求中,key,value中带有特殊符号,请求会报错。接下来通过本文给大家分享解决SpringBoot2.1.3修改tomcat参数支持请求特殊符号 ,需要的朋友可以参考下2019-05-05
最新评论