一介闲人
一介闲人
数据库的记录:
create_time | create_date |
---|---|
2024-04-29 09:26:53 | 2024-04-29 |
2024-05-15 12:12:12 | 2024-05-15 |
查询得到的记录:
{
"createTime": "2024-04-29 22:26:53",
"createDate": "2024-04-29"
},
{
"createTime": "2024-05-16 01:12:12",
"createDate": "2024-05-15"
}
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date createDate;
(1)在配置文件application.properties添加全局的时区配置
spring.jackson.time-zone=Asia/Shanghai
或者
spring.jackson.time-zone=GMT+8
(2)添加配置类
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper() .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS).findAndRegisterModules();
}
}
以上尝试均没有得到效果
数据源配置:
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8&useSSL=false
数据源缺少时区配置,时区不准导致时间不准
在数据源配置是添加时区GMT+8或者serverTimezone=Asia/Shanghai
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
或
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
需要注意的是在配置上直接写GMT+8会创建连接失败,+号会被转义替代,所以需要用%2B代替。
数据库的记录:
create_time | create_date |
---|---|
2024-04-29 09:26:53 | 2024-04-29 |
2024-05-15 12:12:12 | 2024-05-15 |
查询得到的记录:
{
"createTime": "2024-04-29 09:26:53",
"createDate": "2024-04-29"
},
{
"createTime": "2024-05-15 12:12:12",
"createDate": "2024-05-15"
}
评论