java 时间格式化 注解_Java关于时间格式化的方法

目录

一般从数据库获取的时间或日期时间格式化为date或者datetime,为了方便前端渲染,API接口返回的时候需要对日期进行格式化转换,通常会用到 SimpleDateFormat 工具处理。

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

String time = dateFormat.format(new Date());

如果一个DTO类里面有很多关于时间字段需要格式化,就会降低开发效率,产生很多重复臃肿的代码。并且有的项目用Date,有的项目会用LocalDateTime

而此时如果能将时间格式统一配置,就可以省下更多时间专注于业务开发了。

接下来介绍SpringBoot中常用的对时间或日期处理的方式

一、@JsonFormat 注解

JsonFormat注解是jackson包里面的一个注解,需要加上依赖

com.fasterxml.jackson.core

jackson-core

2.11.2

@JsonFormat注解需要用在实体类的时间字段上,对应的字段才能进行格式化。

import com.fasterxml.jackson.annotation.JsonFormat;

import lombok.Data;

import java.time.LocalDateTime;

import java.util.Date;

@Data

public class TestDTO {

@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;

}

public TestDTO get(){

TestDTO testDTO = new TestDTO();

testDTO.setLocalDateTime(LocalDateTime.now());

testDTO.setDate(new Date());

return testDTO;

}

如下所示

cf834f346902391765aa156ff40a04d5.png

还有一种可以全局定义的

二、@JsonComponent 注解 (全局)

配置类

@JsonComponent

public class DateFormatConfig {

@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("UTC");

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());

}

}

这样我们就不用加注解了,也可以实现格式化

@Data

public class TestDTO {

private LocalDateTime localDateTime;

private Date date;

}

48a61e401dfb1a22eb2d38d3c37e9b02.png

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值