关于Springboot日期时间格式化处理方式总结

2020-03-04 12:03:52于丽

项目中使用LocalDateTime系列作为DTO中时间的数据类型,但是SpringMVC收到参数后总报错,为了配置全局时间类型转换,尝试了如下处理方式。

注:本文基于Springboot2.x测试,如果无法生效可能是spring版本较低导致的。PS:如果你的Controller中的LocalDate类型的参数啥注解(RequestParam、PathVariable等)都没加,也是会出错的,因为默认情况下,解析这种参数是使用ModelAttributeMethodProcessor进行处理,而这个处理器要通过反射实例化一个对象出来,然后再对对象中的各个参数进行convert,但是LocalDate类没有构造函数,无法反射实例化因此会报错!!!

本文源码解析部分引用自 Spring中使用LocalDateTime、LocalDate等参数作为入参 ,原文写的很精彩,建议仔细阅读!!!

完成目标

请求入参为 String(指定格式)转 Date,支持get、post(content-type=application/json) 返回数据为Date类型转为指定的日期时间格式字符创 支持Java8 日期 API,如:LocalTime、localDate 和 LocalDateTime

GET请求及POST表单日期时间字符串格式转换

这种情况要和时间作为Json字符串时区别对待,因为前端json转后端pojo底层使用的是Json序列化Jackson工具(HttpMessgeConverter);而时间字符串作为普通请求参数传入时,转换用的是Converter,两者在处理方式上是有区别。

使用自定义参数转换器(Converter)

实现 org.springframework.core.convert.converter.Converter,自定义参数转换器,如下:

@Configuration
public class DateConverterConfig {
  @Bean
  public Converter<String, LocalDate> localDateConverter() {
    return new Converter<>() {
      @Override
      public LocalDate convert(String source) {
        return LocalDate.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
      }
    };
  }

  @Bean
  public Converter<String, LocalDateTime> localDateTimeConverter() {
    return new Converter<>() {
      @Override
      public LocalDateTime convert(String source) {
        return LocalDateTime.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
      }
    };
  }

}

点评:以上两个bean会注入到spring mvc的参数解析器(好像叫做ParameterConversionService),当传入的字符串要转为LocalDateTime类时,spring会调用该Converter对这个入参进行转换。

还可以对前端传递的string进行正则匹配,如yyyy-MM-dd HH:mm:ss、yyyy-MM-dd、 HH:mm:ss等,进行匹配。以适应多种场景。

@Component
public class DateConverter implements Converter<String, Date> {

  private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";

  @Override
  public Date convert(String value) {
    /**
     * 可对value进行正则匹配,支持日期、时间等多种类型转换
     * @param value
     * @return
     */
    SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
    try {
      return formatter.parse(value);
    } catch (Exception e) {
      throw new RuntimeException(String.format("parser %s to Date fail", value));
    }
  }
}