preface : Time format is very frequently used , So we should abstract it , As a global date format , Make time formatting simple without having to make wheels again .
*
use @JsonFormat Comment format time , stay Dao Add annotation to class layer
. But this simplifies the operation of time processing in the actual development logic , There are still disadvantages , That is, each entity class needs to add this annotation . There's a way to avoid this , definition BaseDao Let all entity classes inherit this BaseDao, You just need to BaseDao Just modify and add .
public class test{ @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; } }
* modify Springboot Global configuration .Springboot Date formatting has been provided for us
${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}
, Here we need to make a global configuration . In practical application, if the format needed is :yyyy-MM-dd Date in format , We need to add a specific field property @JsonFormat
Just comment , because @JsonFormat High annotation priority , Will use @JsonFormat The time format of annotation is mainly . @Configuration public
class LocalDateTimeSerializerConfig {
@Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}") private String
pattern; @Bean public LocalDateTimeSerializer localDateTimeDeserializer() {
return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern)); }
@Bean public Jackson2ObjectMapperBuilderCustomizer
jackson2ObjectMapperBuilderCustomizer() { return builder ->
builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer()); } }
epilogue : Attached jdk 8 The method of the new time processing class provided
LocalDate Special processing date ,LocalTime Special processing time ,LocalDateTime Includes date and time , Here are some method references , See the source code directly for specific practical application operations .
Technology
Daily Recommendation