SpringBoot三种方法接口返回日期格式化小结
方法一:@JsonFormat注解
在返回实体的字段上添加@JsonFormat注解。
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date createDate;
pattern是日期格式,timezone是时间分区。格式具体可以参考下图:
方法二:JsonConfig配置
全局配置。好处:无需每个类配置日期格式坏处:不灵活,只能统一。
package com.xy.config; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; import org.springframework.boot.jackson.JsonComponent; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.TimeZone; //jackson日期 @Slf4j @JsonComponent public class JacksonConfig { @Value("${my.jackson.date-format:yyyy-MM-dd HH:mm:ss}") private String pattern; @Bean public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilder() { return builder -> { TimeZone tz = TimeZone.getTimeZone("GMT+8"); DateFormat df = new SimpleDateFormat(pattern); df.setTimeZone(tz); builder.failOnEmptyBeans(false) .failOnUnknownProperties(false) .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .dateFormat(df); }; } @Bean public LocalDateTimeSerializer localDateTimeDeserializer() { return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern)); } @Bean public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() { return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer()); } }
然后配置文件里配置好格式就行。
方法三:yml配置
spring: jackson: date-format: yyyy-MM-dd HH:mm:ss time-zone: GMT+8
UTC和 GMT区别UTC:协调世界时间(UTC)是基于原子时钟的时间计量系统,旨在尽量接近世界时(UT)。UTC的时间尺度是均匀的,不考虑地球自转速度的变化。GMT+8:格林威治平均时间加8小时,即东八区的本地时间。GMT+8通常用于表示中国北京时间UTC:在国际无线电通信、卫星导航等需要高精度时间计量的场合广泛使用。GMT+8:常用于表示中国北京时间,在电子邮件信头、软件显示时间等场合使用。总结:UTC和GMT+8基本相同,UTC更精确而GMT+8常代表北京时间。
总结
三种方法个人推荐第三种。为什么,因为太方便了,另外如果有特殊格式,可以再加@JsonFormat单独注解,会优先以添加了@JsonFormat注解的为准。
到此这篇关于SpringBoot三种方法接口返回日期格式化小结的文章就介绍到这了,更多相关SpringBoot 接口返回日期格式化内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
SpringBoot Security使用MySQL实现验证与权限管理
安全管理是软件系统必不可少的的功能。根据经典的“墨菲定律”——凡是可能,总会发生。如果系统存在安全隐患,最终必然会出现问题,这篇文章主要介绍了SpringBoot安全管理Spring Security基本配置2022-11-11使用redisTemplate的scan方式删除批量key问题
这篇文章主要介绍了使用redisTemplate的scan方式删除批量key问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2023-12-12Java如何利用LocalDate获取某个月的第一天与最后一天日期
这篇文章主要给大家介绍了关于Java如何利用LocalDate获取某个月的第一天与最后一天日期的相关资料,文中通过实例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下2022-01-01
最新评论