需求描述:
WEB
項目中經常遇到前臺以Get
或者Post
方式傳時間值到後臺,後臺採用日期類進行參數接收。
文章目錄
Java8日期類
java8
爲了方便日期處理,引進了日期類LocalDate
和LocalDateTime
,提供了很多方法進行日期的操作,同時也提供了線程安全的格式化類DateTimeFormatter
。
/**
* @implSpec
* This class is immutable and thread-safe.
*
* @since 1.8
*/
public final class LocalDateTime {...}
Get方式傳參格式化
1. @DateTimeFormat 方式
注: @DateTimeFormat爲Spring帶的註解
// 註解可直接作用在方法參數上
@GetMapping("/product/list")
public IPage<Product> listProducts(@DateTimeFormat(pattern = "yyyy-MM-dd") LocalDateTime startTime,
@DateTimeFormat(pattern = "yyyy-MM-dd") LocalDateTime endTime) {
// do something
return null;
}
/**
* 產品查詢參數
*
* @author [email protected]
* @date 2019/10/16
*/
@Data
public class ProductQuery {
@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDateTime startTime;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDateTime endTime;
}
// 註解可作用對象中的屬性上
@GetMapping("/product/list")
public IPage<Product> listProducts(ProductQuery query) {
// do something
return null;
}
此種方式需要在每個參數上進行配置,比較麻煩。
2. WebDataBinder方式(推薦)
/**
* 天貓系統controller切面
*
* @author [email protected]
* @date 2019-08-18
*/
@Slf4j
@ControllerAdvice
public class GlobalControllerAdvice {
@InitBinder
public void initBinder(WebDataBinder webDataBinder) {
webDataBinder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(LocalDate.parse(text, DateTimeFormatter.ISO_DATE));
}
});
webDataBinder.registerCustomEditor(LocalDateTime.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(LocalDateTime.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
}
});
}
}
Post方式傳參格式化
1. @JsonFormat方式
注:@JsonFormat爲Jackson帶的註解
@Data
public class ProductDTO {
// LocalDate可以不用配置,默認格式就是 "yyyy-MM-dd"
// LocalDateTime需要配置,並需要配置到分或者秒 "yyyy-MM-dd HH:mm"
@JsonFormat(pattern = "yyyy-MM-dd")
private LocalDate startTime;
@JsonFormat(pattern = "yyyy-MM-dd")
private LocalDate endTime;
}
此種方式配置需要在每個DTO對象上進行配置,比較麻煩。
2. 全局配置方式(推薦)
/**
* 系統通用簡單配置
*
* @author [email protected]
* @date 2019/10/16
*/
@Configuration
public class TmallConfiguration {
/**
* 此方式可以靈活配置任意類型的序列化反序列化
*/
@Bean
public Jackson2ObjectMapperBuilderCustomizer builderCustomizer() {
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
DateTimeFormatter dateTimeSerializeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
DateTimeFormatter dateTimeDeserializeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
return builder -> {
builder.serializerByType(Long.class, ToStringSerializer.instance);
builder.serializerByType(LocalDate.class, new LocalDateSerializer(dateFormatter));
builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(dateTimeSerializeFormatter));
builder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(dateTimeDeserializeFormatter));
};
}
}