目录
1. SpringBoot
设置后台向前台传递 Date
日期格式
在 SpringBoot
应用中,@RestController
注解的 json
默认序列化中,日期格式默认为:2020-12-03T15:12:26.000+00:00
类型的显示
在实际显示中,我们需要对其转换成我们需要的显示格式
1.1. 方式一:配置文件修改
配置文件配置 application.yml
spring:
# 配置日期格式化
jackson:
date-format: yyyy-MM-dd HH:mm:ss #时间戳统一转换为指定格式
time-zone: GMT+8 # 时区修改为东8区
application.properties
配置方式
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss #时间戳统一转换为指定格式
spring.jackson.time-zone=GMT+8 # 时区修改为东8区
这里需要修改时区 time-zone
:数据库默认时区是格林尼治的时间,如果不设置,会比实际时间少 8
个小时(北京时间)
1.2. 方式二:在实体类上加注解
1.2.1. @JsonFormat
注解
@JsonFormat
来源于 Jackson
,它是一个简单基于 Java 应用库。@JsonFormat
注解用于属性或方法上,将 Date
类型转换为我们需要的类型显示
public class Order {
// timezone:是时间设置为东八区,避免时间在转换中有误差
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createDate;
}
1.2.2. @DateTimeFormat
注解
@DateTimeFormat
是 Spring
自带的处理框架,主要用于将时间格式化
public class Order {
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date createDate;
}
1.2.3. @JSONField
注解
@JSONField
来源于 fastjson
,是阿里的开源框架,主要进行 JSON
解析和序列化
public class Order {
@JSONField(format="yyyy-MM-dd HH:mm:ss")
private Date time;
}
1.2.4. @Temporal
注解
通过 @Temporal
注解,实现日期格式转换,它自带属性参数
public class Order {
@Temporal(TemporalType.TIMESTAMP)
private Date time;
}
2. SpringBoot
配置全局日期格式转换器
配置从页面接收的 String
或 json
格式的日期转换为 Date
类型
2.1. 配置 String
类型表单传参转 Date
的转换器
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
// Converter<S,T> S: 代表的是源,将要转换的数据类型 T:目标类型,将会转成什么数据类型
@Component
public class GlobalFormDateConvert implements Converter<String, Date> {
// 静态初始化定义日期字符串参数列表(需要转换的)
private static final List<