一般从数据库获取的时间或日期时间格式化为日期或者datetime,为了方便前端渲染,API接口返回的时候需要对日期进行格式化转换,通常会用到,<代码> SimpleDateFormat> 代码,工具处理。
SimpleDateFormat dateFormat=new SimpleDateFormat (“yyyy-MM-dd”); 时间=dateFormat字符串。格式(新日期());
如果一个DTO类里面有很多关于时间字段需要格式化,就会降低开发效率,产生很多重复臃肿的代码,并且有的项目用日期,有的项目会用LocalDateTime
而此时如果能将时间格式统一配置,就可以省下更多时间专注于业务开发了。
接下来介绍SpringBoot中常用的对时间或日期处理的方式
JsonFormat注解是杰克逊包里面的一个注解,需要加上依赖
& lt; !——https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core——比; & lt; dependency> & lt; groupId> com.fasterxml.jackson.core & lt; artifactId> jackson-core & lt; version> 2.11.2 & lt;/dependency> >之前@JsonFormat注解需要用在实体类的时间字段上,对应的字段才能进行格式化。
进口com.fasterxml.jackson.annotation.JsonFormat; 进口lombok.Data; 进口java.time.LocalDateTime; 进口java.util.Date; @ data 公开课TestDTO { @JsonFormat (locale=zh型,时区=案窳帜嶂伪曜际奔? 8”,模式=皔yyy-MM-dd”) 私人LocalDateTime createTime; @JsonFormat (locale=zh型,时区=案窳帜嶂伪曜际奔? 8”,模式=皔yyy-MM-dd HH: mm: ss”) 私人updateTime日期; }公共TestDTO get () { TestDTO TestDTO=new TestDTO (); testDTO.setLocalDateTime (LocalDateTime.now ()); testDTO。设置当前日期(新日期()); 返回testDTO; }如下所示
还有一种可以全局定义的
配置类
@JsonComponent 公开课DateFormatConfig { @ value (“$ {spring.jackson。日期格式:yyyy-MM-dd HH: mm: ss}”) 私人字符串模式;//日期类型全局时间格式化 @ bean 公共Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilder () { 恢复建设者→{ 时区tz=TimeZone.getTimeZone (UTC); DateFormat df=new SimpleDateFormat(模式); df.setTimeZone (tz); builder.failOnEmptyBeans(假) .failOnUnknownProperties(假) .featuresToDisable (SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .dateFormat (df); }; }//LocalDate类型全局时间格式化 @ bean 公共LocalDateTimeSerializer localDateTimeDeserializer () { 返回新LocalDateTimeSerializer (DateTimeFormatter.ofPattern(模式)); } @ bean 公共Jackson2ObjectMapperBuilderCustomizer Jackson2ObjectMapperBuilderCustomizer () { 恢复建设者→builder.serializerByType (LocalDateTime。类,localDateTimeDeserializer ()); } }这样我们就不用加注解了,也可以实现格式化
@JsonComponent 公开课DateFormatConfig { @ value (“$ {spring.jackson。日期格式:yyyy-MM-dd HH: mm: ss}”) 私人字符串模式;//日期类型全局时间格式化 @ bean 公共Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilder () { 恢复建设者→{ 时区tz=TimeZone.getTimeZone (UTC); DateFormat df=new SimpleDateFormat(模式); df.setTimeZone (tz); builder.failOnEmptyBeans(假) .failOnUnknownProperties(假) .featuresToDisable (SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .dateFormat (df); }; }//LocalDate类型全局时间格式化 @ bean 公共LocalDateTimeSerializer localDateTimeDeserializer () { 返回新LocalDateTimeSerializer (DateTimeFormatter.ofPattern(模式)); } @ bean 公共Jackson2ObjectMapperBuilderCustomizer Jackson2ObjectMapperBuilderCustomizer () { 恢复建设者→builder.serializerByType (LocalDateTime。类,localDateTimeDeserializer ()); } }
详解Java关于时间格式化的方法