前言:时间格式化是使用频率非常高的,所以就应将它抽象出来,作为全局的日期格式化处理,让时间格式化变得既简单又不用重复造轮子。
-
使用
@JsonFormat
注解格式化时间,在Dao类层中添加注解。但这样虽然简化了在实际开发逻辑中对时间处理的操作,仍存在弊端,那就是每个实体类都需要新增此注解。有个思路可以避免此情况的产生,定义BaseDao让所有的实体类去继承此BaseDao,只需要在BaseDao中修改新增即可。
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;
}
}
- 修改
Springboot
全局配置。Springboot
已经为我们提供了日期格式化${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}
,这里我们需要进行全局配置。这种在实际应用中如果遇到需要的格式为:yyyy-MM-dd格式的日期,我们就需要在特定的字段属性添加@JsonFormat
注解即可,因为@JsonFormat
注解优先级比较高,会以@JsonFormat
注解标注的时间格式为主。
@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());
}
}
结语:附带jdk 8 所提供的新版时间处理类的方法
LocalDate专门处理日期,LocalTime专门处理时间,LocalDateTime包含了日期和时间,下面提供一些方法参考,具体相关实际应用操作可直接看源码。