详解Java关于时间格式化的方法

所属分类: 软件编程 / java 阅读数: 46
收藏 0 赞 0 分享

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

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String time = dateFormat.format(new Date());

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

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

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

一、@JsonFormat 注解

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

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.11.2</version>
</dependency>

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

如下所示

还有一种可以全局定义的

二、@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());
  }
}

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

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

到此这篇关于详解Java关于时间格式化的方法的文章就介绍到这了,更多相关Java 时间格式化内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

更多精彩内容其他人还在看

详解Spring依赖注入:@Autowired,@Resource和@Inject区别与实现原理

这篇文章主要介绍了详解Spring依赖注入:@Autowired,@Resource和@Inject区别与实现原理,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

了解spring中的CloudNetflix Hystrix弹性客户端

这篇文章主要介绍了了解spring中的CloudNetflix Hystrix弹性客户端,客户端弹性模式是在远程服务发生错误或表现不佳时保护远程资源(另一个微服务调用或者数据库查询)免于崩溃。,需要的朋友可以参考下
收藏 0 赞 0 分享

Spark学习笔记Spark Streaming的使用

这篇文章主要介绍了Spark学习笔记Spark Streaming的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

通过实例讲解springboot整合WebSocket

这篇文章主要介绍了通过实例讲解springboot整合WebSocket,WebSocket为游览器和服务器提供了双工异步通信的功能,即游览器可以向服务器发送消息,服务器也可以向游览器发送消息。,需要的朋友可以参考下
收藏 0 赞 0 分享

java虚拟机学习笔记进阶篇

在本篇内容里小编给大家分享了关于java虚拟机学习笔记的进阶内容,需要的朋友们跟着学习下。
收藏 0 赞 0 分享

java虚拟机学习高级篇

在本篇文章里小编给大家整理了关于java虚拟机学习高级篇的相关内容,有兴趣的朋友们跟着学习参考下。
收藏 0 赞 0 分享

java虚拟机中多线程总结

在本篇内容中小编给大家分享的是关于java虚拟机中多线程的知识点总结内容,需要的朋友们参考学习下。
收藏 0 赞 0 分享

java虚拟机多线程进阶篇总结

在本篇内容里小编给大家整理了关于java虚拟机多线程进阶篇的相关知识点内容,有兴趣的朋友们跟着参考下。
收藏 0 赞 0 分享

java数据结构和算法中数组的简单入门

在本文里小编给大家整理了关于java数据结构和算法中数组的简单入门知识点整理,需要的朋友们学习下。
收藏 0 赞 0 分享

java数据结构和算法中哈希表知识点详解

在本篇文章里小编给大家分享了关于java数据结构和算法中哈希表的相关知识点内容,需要的朋友们学习下。
收藏 0 赞 0 分享
查看更多