在项目中日期格式化是最常见的问题,之前涉及的java.util.Date 和 java.util.Calendar 类易用性差,不支持时区,非线程安全,对日期的计算方式繁琐,而且容易出错,因为月份是从0开始的,从 Calendar 中获取的月份需要加一才能表示当前月份。
在 JDK8 中,一个新的重要特性就是引入了全新的时间和日期API,它被收录在 java.time 包中,借助新的时间和日期API可以以更简洁的方法处理时间和日期。
下面我们通过一些配置实现对日期类型LocalDateTime的格式化
导入依赖
新建一个spring boot项目导入web依赖即可
org.springframework.boot
spring-boot-starter-web
配置方案一
定义一个配置类,在里面定义两个 Bean 即可完成全局日期格式化处理,同时还兼顾了 Date 和 LocalDateTime 并存
packagecom.carry.config;importjava.time.LocalDateTime;importjava.time.format.DateTimeFormatter;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importcom.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
@Configurationpublic classLocalDateTimeSerializerConfig {
@Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")privateString pattern;//方案一
@BeanpublicLocalDateTimeSerializer localDateTimeDeserializer() {return newLocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
}
@BeanpublicJackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());
}
}
实体类
packagecom.carry.dto;importjava.time.LocalDateTime;public classOrder {privateLocalDateTime createTime;publicLocalDateTime getCreateTime() {returncreateTime;
}public voidsetCreateTime(LocalDateTime createTime) {this.createTime =createTime;
}
}
控制层
packagecom.carry.controller;importjava.time.LocalDateTime;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;importcom.carry.dto.Order;
@RestController
@RequestMapping("/orders")public classOrderController {
@GetMappingpublicOrder query() {
Order order= newOrder();
order.setCreateTime(LocalDateTime.now());returnorder;
}
}
测试
配置方案二
有时候,我们对日期格式要做特殊的处理,全局的格式化方式无法满足我们需求是,使用该方案是非常好的选择,通过 @JsonFormat 注解我们可以更为精准的为日期字段格式化,它的优先级比方案一高,二者可结合使用
packagecom.carry.dto;importjava.time.LocalDateTime;importcom.fasterxml.jackson.annotation.JsonFormat;public classOrder {
@JsonFormat(pattern= "yyyy-MM-dd")privateLocalDateTime createTime;publicLocalDateTime getCreateTime() {returncreateTime;
}public voidsetCreateTime(LocalDateTime createTime) {this.createTime =createTime;
}
}
配置方案三
其实和第一种类似,只不过第一种的写法更加优雅简洁,如果有多种类型需要做统一格式化处理,这种方案也不是不可以考虑(经测试不能与方案二同时使用)
packagecom.carry.config;importjava.io.IOException;importjava.time.LocalDateTime;importjava.time.format.DateTimeFormatter;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.context.annotation.Primary;importcom.fasterxml.jackson.core.JsonGenerator;importcom.fasterxml.jackson.core.JsonParser;importcom.fasterxml.jackson.databind.DeserializationContext;importcom.fasterxml.jackson.databind.JsonDeserializer;importcom.fasterxml.jackson.databind.JsonSerializer;importcom.fasterxml.jackson.databind.ObjectMapper;importcom.fasterxml.jackson.databind.SerializerProvider;importcom.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
@Configurationpublic classLocalDateTimeSerializerConfig {
@Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")privateString pattern;//方案三
@Bean
@PrimarypublicObjectMapper serializingObjectMapper() {
ObjectMapper objectMapper= newObjectMapper();
JavaTimeModule javaTimeModule= newJavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, newLocalDateTimeSerializer());
javaTimeModule.addDeserializer(LocalDateTime.class, newLocalDateTimeDeserializer());
objectMapper.registerModule(javaTimeModule);returnobjectMapper;
}public class LocalDateTimeSerializer extends JsonSerializer{
@Overridepublic voidserialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers)throwsIOException {
gen.writeString(value.format(DateTimeFormatter.ofPattern(pattern)));
}
}public class LocalDateTimeDeserializer extends JsonDeserializer{
@OverridepublicLocalDateTime deserialize(JsonParser p, DeserializationContext deserializationContext)throwsIOException {returnLocalDateTime.parse(p.getValueAsString(), DateTimeFormatter.ofPattern(pattern));
}
}
}
推荐使用方案一与方案二