springboot 全域性時間格式化
阿新 • • 發佈:2021-10-27
方法一:配置
這種方式只對 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>