springboot中关于新老时间API添加对应注解,解决返回时间参数格式问题

参考 https://blog.csdn.net/u010647035/article/details/98204999

  • jdk8 新时间api 、Date日期api
  • spring boot中参数传递和返回问题
  • 相关注解(支持新老时间api)
    • @DateTimeFormat
      • 单个时间入参格式化
      • 400(前后参数不一致会报400)
    • @JsonFormat 出参格式化
      • 出参的格式化,返回时间格式自己想要的
    • @InitBinder 表单数据处理
      • 处理所有表入参格式化
  • 全局的入参格式化和出参格式化实现
  • 表单参数格式化 @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)));
       };
    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值