一、说在前面
springboot的自动注入中内嵌了格式转化器,如果不做配置按照系统的默认时间格式请求和响应数据。
形如:Wed Mar 20 10:32:29 CST 2024
也就是说如果请求响应的数据和这个格式一样,就能成功,就不会报404
内嵌格式转化器:
支持自定义格式转化器的注册:
二、前端到后端日期格式转换
方法一:配置文件方法(在application.yml配置文件中)
spring:
mvc:
date-format: yyyy-MM-dd
方法二:在实体类中日期属性前加DateTimeFormat注解
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date birth;
方法三:自定义配置文件实现WebMvcConfigurer接口,重新格式转化器
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addFormatter(new Formatter<Date>() {
@Override
public String print(Date date, Locale locale) {
return null;
}
@Override
public Date parse(String s, Locale locale) throws ParseException {
return new SimpleDateFormat("yyyy-MM-dd").parse(s);
}
});
}
三、后端到前端日期格式转换
方法一:消息转化器和fastjson结合
fastjson是阿里的开源包,用于对json格式数据的解析处理。
pom.xml中引入fastjson依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
在自定义配置类中配置消息转化器
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter fc = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
fc.setFastJsonConfig(fastJsonConfig);
converters.add(fc);
}
在实体类上加@jsonfield注解
@JSONField(format = "yyyy-MM-dd")
private Date date;
四、一个注解请求响应双向日期格式转换
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8"))
private Date birth;
//timezone用于指定是区,上面取值是东八区北京时间
注意在使用这个注解时请求的数据和响应的数据必须是json格式的。