方法一:配置
这种方式只对 Date 类型生效
spring: jackson: date-format: yyyy-MM-dd HH:mm:ss time-zone: GMT+8
方法二:@JsonFormat
部分格式化:@JsonFormat 注解需要用在实体类的时间字段上,对应的字段才能进行格式化。
@Getter @Setter public class TestTime { @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") private Date date; private LocalDateTime localDateTime; @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyyMMdd") private LocalDate localDate; @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "HHmmss") private LocalTime localTime; }
方法三:@JsonComponent
使用 @JsonComponent 注解自定义一个全局格式化类,分别对 Date 和 LocalDate 类型做格式化处理。
@JsonComponent public class JsonComponentConfig { @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}") private String pattern; /** * 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 类型全局时间格式化 */ public LocalDateTimeSerializer localDateTimeDeserializer() { return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern)); } @Bean public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() { return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer()); } }