参考 https://blog.csdn.net/u010647035/article/details/98204999
- jdk8 新时间api 、Date日期api
- spring boot中参数传递和返回问题
- 相关注解(支持新老时间api)
- @DateTimeFormat
- 单个时间入参格式化
- 400(前后参数不一致会报400)
- @JsonFormat 出参格式化
- 出参的格式化,返回时间格式自己想要的
- @InitBinder 表单数据处理
- 处理所有表入参格式化
- @DateTimeFormat
- 全局的入参格式化和出参格式化实现
- 表单参数格式化 @InitBinder
//后台时间格式化(只加在单个字段上)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
// private Date createTime;
private LocalDateTime createTime
除了单个字段加也可以配置全局的
入参:
/**
* @className: InitBinderAdviseController
* @description: 拦截全局 全局加入参时间格式化
* @author: lxt
* @create: 2021-03-29 14:28
**/
/**
* @ControllerAdvice 是spring 3.2提供的新注解,他是一个controller增强器
* ,可以对controller中使用到@RequestMapping注解的一下方法做逻辑处理
*/
@ControllerAdvice
public class InitBinderAdviseController {
/**
* 将前台传递过来的日期格式的字符串,自动转化为时间类型
*/
@InitBinder
public void initBinder(WebDataBinder binder)
{
// Date 类型转换
DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
binder.registerCustomEditor(Date.class,new CustomDateEditor(dateFormat, true));
// LocalDateTime 类型转换
binder.registerCustomEditor(LocalDateTime.class, new PropertyEditorSupport()
{
@Override
public void setAsText(String text)
{
if(!StringUtils.isEmpty(text)){
setValue(LocalDateTime.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
}
}
});
}
}
在application.yml 中spring下面添加Jackson配置全局出参时间格式化
出参(老的时间格式api,Date):
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
出参(新的时间格式api,LocalDateTime):
配置类WebMvcConfig中添加如下代码
/**
* @className: WebMvcConfig
* @description:
* @author: lxt
* @create: 2021-03-27 10:47
**/
@Configuration //@Configuration标注在类上,相当于把该类作为spring的xml配置文件中的<beans>,作用为:配置spring容器
public class WebMvcConfig implements WebMvcConfigurer {
private static final String dateFormat = "yyyy-MM-dd";
private static final String dateTimeFormat = "yyyy-MM-dd HH:mm:ss";
/**
* @Bean <bean id="xxx"></bean>
* @return
*/
@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
return builder -> {
builder.simpleDateFormat(dateTimeFormat);
builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(dateFormat)));
builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateTimeFormat)));
};
}
}