前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >全局时间格式化

全局时间格式化

作者头像
CBeann
发布2023-12-25 18:02:16
1690
发布2023-12-25 18:02:16
举报
文章被收录于专栏:CBeann的博客

需求

经常会需要后端给前端传时间,有各种类型的时候,date、java8中LocalDateTime等等,虽然挺简单一个小事,但是也挺繁琐的,毕竟大家容易犯懒。

实践

代码(SpringBoot)

添加jackson依赖
代码语言:javascript
复制
  <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.10.2</version>
        </dependency>
修改application.properties
代码语言:javascript
复制
######################################
#jackson.date-format
######################################
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
时间格式化配置类
代码语言:javascript
复制
package com.example.jsondemo;

import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
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.context.annotation.Configuration;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.TimeZone;

/**
 * @author CBeann
 * @create 2020-09-05 19:23
 */
@Configuration
@JsonComponent
public class DateFormatConfig {


    @Value("${spring.jackson.date-format}")
    private String pattern;

    /**
     * @description date 类型全局时间格式化
     * @date 2020-09-05 19:23
     */
    @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);
        };
    }

    /**
     * @description LocalDate 类型全局时间格式化
     * @date 2020-09-05 19:23
     */
    @Bean
    public LocalDateTimeSerializer localDateTimeDeserializer() {
        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());
    }
}
实体类
代码语言:javascript
复制
@Data
public class Student {

    private String name;
    private Date date;
    private LocalDateTime localDateTime;
    private LocalDate localDate;
    private LocalTime localTime;
}
测试
代码语言:javascript
复制
@RequestMapping("/hello")
    public Object jsonObject() {
        Student student = new Student();
        student.setDate(new Date());
        student.setLocalDate(LocalDate.now());
        student.setLocalDateTime(LocalDateTime.now());
        student.setLocalTime(LocalTime.now());

        return student;
    }
测试结果

使用自定义格式

代码语言:javascript
复制
@JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd")
代码语言:javascript
复制
@Data
public class Student {

    private String name;
    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd")
    private Date date;
    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd")
    private LocalDateTime localDateTime;
    private LocalDate localDate;
    private LocalTime localTime;
}

参考

3种 Springboot 全局时间格式化方式,别再写重复代码了

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-03-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 需求
  • 实践
    • 代码(SpringBoot)
      • 添加jackson依赖
      • 修改application.properties
      • 时间格式化配置类
      • 实体类
      • 测试
      • 测试结果
    • 使用自定义格式
    • 参考
    相关产品与服务
    腾讯云服务器利旧
    云服务器(Cloud Virtual Machine,CVM)提供安全可靠的弹性计算服务。 您可以实时扩展或缩减计算资源,适应变化的业务需求,并只需按实际使用的资源计费。使用 CVM 可以极大降低您的软硬件采购成本,简化 IT 运维工作。
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档