方法一:配置
这种方式只对 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()); } }
完整项目:
新增OrderInfo
public class OrderInfo {
//@JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createTime;
//@JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
public LocalDateTime getCreateTime() {
return createTime;
}
public void setCreateTime(LocalDateTime createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
新增controller
@RestController
public class TimeTestClass {
@GetMapping("/timeTest")
public OrderInfo timeTest(){
OrderInfo orderInfo = new OrderInfo();
orderInfo.setCreateTime(LocalDateTime.now());
orderInfo.setUpdateTime(new Date());
return orderInfo;
}
}
添加依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.12.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.12.3</version>
</dependency>