SpringBoot将Jackson用作默认的JSON工具,我们可以设置全局格式
application.properties

spring.jackson.date-format=yyyy-MM-dd HH:mm:ss

application.yml

spring:
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss

但是设置只能使用它格式化Java类型 java.util.Date 或 java.util.Calendar,不适用于Java8日期类型,如LocalDate和LocalDateTime。

由于MybatisPlus新 默认生成的是 LocalDateTime,上述设置无法生效。

方案:

  • 实体字段上使用注解

      @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
      private LocalDateTime createTime;
      @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
      private LocalDateTime updateTime;

    或者

  • 实现 Jackson2ObjectMapperBuilderCustomizer

    @Configuration
    public class JacksonFormatConfig  implements  Jackson2ObjectMapperBuilderCustomizer{
      private static final String DATE_FORMAT = "yyyy-MM-dd";
      private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    
      @Override
      public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
          jacksonObjectMapperBuilder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(DATE_FORMAT)));
          jacksonObjectMapperBuilder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)));
      }
    }
    

    https://docs.spring.io/spring-framework/docs/5.3.15/javadoc-api/org/springframework/http/converter/json/Jackson2ObjectMapperBuilder.html