后端时间格式化问题?一个配置解决它

59 阅读1分钟

后端返回的字符串总是不规范?总要前端自己去格式化?把这篇文章发给TA,让TA学会使用全局时间格式化。

(像这种情况,其实困扰了我挺久的,添加很多配置,什么拦截器什么的,都不是很管用)

直到我使用jackson的jsonFormat,就能对时间进行格式化。 (不过这种我配置是不生效的,大家可根据自己情况来)

全局格式化

/**
 * 时间格式化配置
 */
@JsonComponent
public class DateFormatConfig {
  @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
  private String pattern;
  @Resource
  @Lazy
  private LocalDateTimeSerializer localDateTimeDeserializer;

  /**
   * date 类型全局时间格式化
   */
  @Bean
  public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilder() {

    return builder -> {
      TimeZone tz = TimeZone.getTimeZone("UTC");
      DateFormat df = new SimpleDateFormat(pattern);
      df.setTimeZone(tz);
      builder.failOnEmptyBeans(false)
          .failOnUnknownProperties(false)
          .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
          .dateFormat(df);
    };
  }

  /**
   * LocalDate 类型全局时间格式化
   */
  @Bean
  public LocalDateTimeSerializer localDateTimeDeserializer() {
    return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
  }

  @Bean
  public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
    return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer);
  }
}

在实体类上,如果需要指定另外的格式方式,也可使用@JsonFormat注解

public class UserVO implements Serializable {
  private String username;
  private String nickname;
  private String role;
  private String phone;
  private String email;
  // 已全局配置时间格式化,亦可使用 @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd")的方式
  private LocalDateTime createTime;
}