千家信息网

SpringBoot时间格式化的方法有哪些

发表于:2025-11-16 作者:千家信息网编辑
千家信息网最后更新 2025年11月16日,这篇文章主要介绍了SpringBoot时间格式化的方法有哪些的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇SpringBoot时间格式化的方法有哪些文章都会有所收获,下面
千家信息网最后更新 2025年11月16日SpringBoot时间格式化的方法有哪些

这篇文章主要介绍了SpringBoot时间格式化的方法有哪些的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇SpringBoot时间格式化的方法有哪些文章都会有所收获,下面我们一起来看看吧。

时间格式化在项目中使用频率是非常高的,当我们的 API 接口返回结果,需要对其中某一个 date 字段属性进行特殊的格式化处理,通常会用到 SimpleDateFormat 工具处理。

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");Date stationTime = dateFormat.parse(dateFormat.format(PayEndTime()));

可一旦处理的地方较多,不仅 CV 操作频繁,还产生很多重复臃肿的代码,而此时如果能将时间格式统一配置,就可以省下更多时间专注于业务开发了。

可能很多人觉得统一格式化时间很简单啊,像下边这样配置一下就行了,但事实上这种方式只对 date 类型生效。

spring.jackson.date-format=yyyy-MM-dd HH:mm:ssspring.jackson.time-zone=GMT+8

而很多项目中用到的时间和日期API 比较混乱, java.util.Datejava.util.Calendarjava.time LocalDateTime 都存在,所以全局时间格式化必须要同时兼容性新旧 API

看看配置全局时间格式化前,接口返回时间字段的格式。

@Datapublic class OrderDTO {    private LocalDateTime createTime;    private Date updateTime;}

很明显不符合页面上的显示要求

一、@JsonFormat 注解

@JsonFormat 注解方式严格意义上不能叫全局时间格式化,应该叫部分格式化,因为@JsonFormat 注解需要用在实体类的时间字段上,而只有使用相应的实体类,对应的字段才能进行格式化。

@Datapublic class OrderDTO {    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd")    private LocalDateTime createTime;    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")    private Date updateTime;}

字段加上 @JsonFormat 注解后,LocalDateTimeDate 时间格式化成功。

二、@JsonComponent 注解(推荐)

这是我个人比较推荐的一种方式,前边看到使用 @JsonFormat 注解并不能完全做到全局时间格式化,所以接下来我们使用 @JsonComponent注解自定义一个全局格式化类,分别对 DateLocalDate 类型做格式化处理。

@JsonComponentpublic class DateFormatConfig {    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")    private String pattern;    /**     * @author xiaofu     * @description date 类型全局时间格式化     * @date 2020/8/31 18:22     */    @Bean    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilder() {        return builder -> {            TimeZone tz = TimeZone.getTimeZone("UTC");            DateFormat df = new SimpleDateFormat(pattern);            df.setTimeZone(tz);            builder.failOnEmptyBeans(false)                    .failOnUnknownProperties(false)                    .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)                    .dateFormat(df);        };    }    /**     * @author xiaofu     * @description LocalDate 类型全局时间格式化     * @date 2020/8/31 18:22     */    @Bean    public LocalDateTimeSerializer localDateTimeDeserializer() {        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));    }    @Bean    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {        return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());    }}

看到 DateLocalDate 两种时间类型格式化成功,此种方式有效。

但还有个问题,实际开发中如果我有个字段不想用全局格式化设置的时间样式,想自定义格式怎么办?

那就需要和 @JsonFormat 注解配合使用了。

@Datapublic class OrderDTO {    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd")    private LocalDateTime createTime;    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd")    private Date updateTime;}

从结果上我们看到 @JsonFormat 注解的优先级比较高,会以 @JsonFormat 注解的时间格式为主。

三、@Configuration 注解

这种全局配置的实现方式与上边的效果是一样的。

"

注意:在使用此种配置后,字段手动配置@JsonFormat 注解将不再生效。

"

@Configurationpublic class DateFormatConfig2 {    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")    private String pattern;    public static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    @Bean    @Primary    public ObjectMapper serializingObjectMapper() {        ObjectMapper objectMapper = new ObjectMapper();        JavaTimeModule javaTimeModule = new JavaTimeModule();        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());        objectMapper.registerModule(javaTimeModule);        return objectMapper;    }    /**     * @author xiaofu     * @description Date 时间类型装换     * @date 2020/9/1 17:25     */    @Component    public class DateSerializer extends JsonSerializer {        @Override        public void serialize(Date date, JsonGenerator gen, SerializerProvider provider) throws IOException {            String formattedDate = dateFormat.format(date);            gen.writeString(formattedDate);        }    }    /**     * @author xiaofu     * @description Date 时间类型装换     * @date 2020/9/1 17:25     */    @Component    public class DateDeserializer extends JsonDeserializer {        @Override        public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {            try {                return dateFormat.parse(jsonParser.getValueAsString());            } catch (ParseException e) {                throw new RuntimeException("Could not parse date", e);            }        }    }    /**     * @author xiaofu     * @description LocalDate 时间类型装换     * @date 2020/9/1 17:25     */    public class LocalDateTimeSerializer extends JsonSerializer {        @Override        public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {            gen.writeString(value.format(DateTimeFormatter.ofPattern(pattern)));        }    }    /**     * @author xiaofu     * @description LocalDate 时间类型装换     * @date 2020/9/1 17:25     */    public class LocalDateTimeDeserializer extends JsonDeserializer {        @Override        public LocalDateTime deserialize(JsonParser p, DeserializationContext deserializationContext) throws IOException {            return LocalDateTime.parse(p.getValueAsString(), DateTimeFormatter.ofPattern(pattern));        }    }}

关于"SpringBoot时间格式化的方法有哪些"这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对"SpringBoot时间格式化的方法有哪些"知识都有一定的了解,大家如果还想学习更多知识,欢迎关注行业资讯频道。

时间 格式 注解 全局 类型 字段 配置 方式 方法 处理 知识 成功 内容 实体 接口 更多 篇文章 结果 项目 开发 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 工行软件开发职位晋升 车主用什么软件开发票 网络安全宣传作品征集手抄报 软件开发都是在哪交流的 深圳意志流网络技术有限公司 学软件开发专科学费多少钱 数据库外键是父表主键 软件开发通常由4个阶段组成 服务器连接管理工具源码 导入数据库语句python 数据库用户口令错误重新登录 江西审批管控软件开发平台 河北二本院校软件开发专业 国家网络安全与什么并重 计算机软件开发前景如何 常州小学生网络安全知识 高中网络安全手抄报模板大全 百度网络安全验证什么东西 关于网络安全方面的对联 服务器磁盘分区用gpt么 服务器不小心按到白灯 如何使用樱花开服务器 oracle微服务数据库 数据库创建表的列写中文 系统软件开发国家规范 天津软件开发公司厂家报价 福柯网络技术 冬季运动项目数据库 重返帝国服务器是不是炸了 分布式数据库灾备
0