springboot 日期类型处理

1. 日期类型输出参数处理

默认日期格式只支持:2017-07-01T10:10:01

修改为2017-07-01 10:10:01

只需要修改配置文件即可:

spring:
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8

 

1. 日期类型输入参数处理

默认日期格式只支持:2017/07/01

修改为支持2017-07-01日期格式

@ControllerAdvice
public class GlobalHandler {

    @InitBinder
    public void initBinder(WebDataBinder binder) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));

    }
}

看到网友介绍的可以使用registerCustomEditor的重载方法,使用日期类型支持多种格式,但好像是需要在具体的日期字段上添加注解才可行,我没有尝试。

还有网友介绍的:通过继承WebMvcConfigurationSupport

@Configuration 
public class WebMvcConfig extends WebMvcConfigurationSupport {

    /**
     * 添加自定义的Converters和Formatters.
     */
    @Override
    protected void addFormatters(FormatterRegistry registry) {
       registry.addConverter(new StringToDateConverter());
    }
}

这种方式会使用application.yml对日期的配置失效。

为了解决配置失效的问题,尝试实现WebMvcConfigurer,但又报swagger的错误。

所以最后选择了上述的方案。

posted @ 2018-12-25 10:56  二奎  阅读(395)  评论(0编辑  收藏  举报