SpringBoot时间格式化的5种方法


1.前端时间格式化

JS 版时间格式化

 1 function dateFormat(fmt, date) {
 2     let ret;
 3     const opt = {
 4         "Y+": date.getFullYear().toString(),        //
 5         "m+": (date.getMonth() + 1).toString(),     //
 6         "d+": date.getDate().toString(),            //
 7         "H+": date.getHours().toString(),           //
 8         "M+": date.getMinutes().toString(),         //
 9         "S+": date.getSeconds().toString()          //
10         // 有其他格式化字符需求可以继续添加,必须转化成字符串
11     };
12     for (let k in opt) {
13         ret = new RegExp("(" + k + ")").exec(fmt);
14         if (ret) {
15             fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
16         };
17     };
18     return fmt;
19 }

方法调用:

1 let date = new Date();
2 dateFormat("YYYY-mm-dd HH:MM:SS", date);
3   
4 >>> 2021-07-25 21:45:12

2.SimpleDateFormat格式化

1 // 定义时间格式化对象和定义格式化样式
2 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
3 // 格式化时间对象
4 String date = dateFormat.format(new Date())

3.DateTimeFormatter格式化

 1 @RequestMapping("/list")
 2 public List getList() {
 3     // 定义时间格式化对象
 4     DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
 5     List list = userMapper.getList();
 6     // 循环执行时间格式化
 7     list.forEach(item -> {
 8         // 使用预留字段 ctime 接收 createtime 格式化的时间(Date->String)
 9         item.setCtime(dateFormat.format(item.getCreatetime()));
10         item.setUtime(dateFormat.format(item.getUpdatetime()));
11     });
12     return list;
13 }

4.全局时间格式化

我们可以不改任何代码,只需要在配置文件中设置一下就可以实现时间格式化的功能了。

首先,我们找到 Spring Boot 的配置文件 application.properties(或 application.yml),只需要在 application.properties 配置文件中添加以下两行配置:

# 格式化全局时间字段
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
# 指定时间区域类型
spring.jackson.time-zone=GMT+8

实现原理分析

这是因为 Controller 在返回数据时,会自动调用 Spring Boot 框架中内置的 JSON 框架 Jackson,对返回的数据进行统一的 JSON 格式化处理,在处理的过程中它会判断配置文件中是否设置了“spring.jackson.date-format=yyyy-MM-dd HH:mm:ss”,如果设置了,那么 Jackson 框架在对时间类型的字段输出时就会执行时间格式化的处理,这样我们就通过配置来实现全局时间字段的格式化功能了。

为什么要指定时间区域类型“spring.jackson.time-zone=GMT+8”呢?

最现实的原因是,如果我们不指定时间区域类型,那么查询出来的时间就会比预期的时间少 8 个小时,这因为我们(中国)所处的时间区域比世界时间少 8 个小时导致的,而当我们设置了时区之后,我们的时间查询才会和预期时间保持一致。

 

GMT 是什么?

时间区域设置中的“GMT” 是什么意思?

Greenwich Mean Time (GMT) 格林尼治时间,也叫做世界时间。

5.部分时间格式化

某些场景下,我们不需要对全局的时间都进行统一的处理,这种情况我们可以使用注解的方式来实现部分时间字段的格式化。

我们需要在实体类 UserInfo 中添加 @JsonFormat 注解,这样就可以实现时间的格式化功能了,实现代码如下:

 1 import com.fasterxml.jackson.annotation.JsonFormat;
 2 import lombok.Data;
 3 
 4 import java.util.Date;
 5 
 6 @Data
 7 public class UserInfo {
 8     private int id;
 9     private String username;
10     // 对 createtime 字段进行格式化处理
11     @JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss", timezone = "GMT+8")
12     private Date createtime;
13     private Date updatetime;
14 }