时间格式化

文章介绍了在Java中使用SpringBoot进行时间格式化的两种方法:一是通过在实体类的特定字段添加`@JsonFormat`注解进行局部格式化;二是通过全局配置类实现所有日期时间的统一格式化,避免在每个实体类中重复注解。配置中包含了时区设置和日期模板定义。
摘要由CSDN通过智能技术生成

image.png

方式一:局部格式化时间

在domain实体类中,哪些字段需要进行时间格式化的话,加上**@JsonFormat**注解即可:

@Data
public class BlogArticle {
    private Long userId;
    //文章内容
    private String articleContent;
    //最后更新时间
    //timezone表示时区"GMT+8"是东八区北京时间
    @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
    private Date updateTime = new Date();
    //文章类型
    private Long articleType;
    //文章点赞数
    private Integer articleStarNum;
}

方式二:全局格式化时间

用上面方式可以解决问题,但是如果每个实体类都需要这样打注解的话,会非常繁琐
此时我们可以使用全局日期时间格式化,看下面介绍
在需要全局格式化的SpringBoot项目中,在配置config包中新建如下配置类:

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 java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.TimeZone;

/**
 * @description: 日期时间全局格式化
 */
@JsonComponent
public class LocalDateTimeSerializerConfig {

    // 格式模板
    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private String pattern;

    /**
     * Date 类型全局时间格式化
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilder() {
        return builder -> {
            TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");//获取时区
            DateFormat df = new SimpleDateFormat(pattern);//设置格式化模板
            df.setTimeZone(tz);
            builder.failOnEmptyBeans(false)
                    .failOnUnknownProperties(false)
                    .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
                    .dateFormat(df);
        }; }

    /**
     * LocalDate 类型全局时间格式化
     */
    @Bean
    public LocalDateTimeSerializer localDateTimeDeserializer() {
        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());
    }
}

两种方式都存在时,方式一优先生效

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值