关于springboot的一些时间问题

最近项目里又发现一个问题,本地运行时间和服务器上的时区不一样,导致显示的时间不同,还有各种时间格式的问题。在这里整理一下。

统一时区

数据库连接url加上:

&useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=UTF8

然后在application启动类设置时区:

@PostConstruct
void started() {
    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
}

数据库时区

在mysql中查看关于时区的设置
show variables like '%time_zone%';

在这里插入图片描述

可以发现如果没有设置的话默认使用的时区是CST,可问题是CST是一个很复杂的时区。

科普一下:CST可以为如下4个不同的时区的缩写:
美国中部时间:Central Standard Time (USA) UT-6:00

澳大利亚中部时间:Central Standard Time (Australia) UT+9:30

中国标准时间:China Standard Time UT+8:00

古巴标准时间:Cuba Standard Time UT-4:00

这样的话我们就需要去修改一下,改成 +0:00,或者 +8:00,都是可以的。

--自MySQL 8.0 GA版本开始支持将参数写入并且持久化:
mysql> set persist time_zone='+0:00';

也可以直接修改配置文件

default-time-zone = '+8:00'

然后重启。

时间格式

SimpleDateFormatDateTimeFormatter时间格式化

这个没什么说的,他们两的区别主要是一个不是线程安全,DateTimeFormatter是线程安全的。

他们还可以设置时区

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));

配置文件的设置

spring:
  jackson:
    #  格式化返回时间 yyyy-MM-dd HH:mm:ss
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8

优点是统一, Controller 在返回数据时,会自动调用 Spring Boot 框架中内置的 JSON 框架 Jackson,对返回的数据进行统一的 JSON 格式化处理

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 中使用 LocalDateTime 进行时间转换时,需要注意以下几点: 1. LocalDateTime 与数据库的时间类型转换:在使用 LocalDateTime 与数据库进行交互时,需要将 LocalDateTime 转换为对应的数据库时间类型,如 MySQL 中的 DATETIME 或 TIMESTAMP。可以使用 JPA 中的 @Convert 注解或自定义 Converter 进行转换。 2. LocalDateTime 与 JSON 数据的转换:在使用 Spring Boot 进行 Web 开发时,需要将 LocalDateTime 转换为 JSON 数据,或将 JSON 数据转换为 LocalDateTime。可以使用 Jackson 库中的 @JsonFormat 注解或自定义 JsonSerializer 和 JsonDeserializer 进行转换。 3. LocalDateTime 的时区问题:在使用 LocalDateTime 进行时间转换时,需要考虑时区的问题。可以使用时区相关的类如 ZoneId 和 ZonedDateTime 进行转换。 示例代码: 将 LocalDateTime 转换为数据库时间类型: ```java @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @Convert(converter = LocalDateTimeConverter.class) private LocalDateTime createTime; // getter 和 setter } @Converter public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> { @Override public Timestamp convertToDatabaseColumn(LocalDateTime localDateTime) { return localDateTime == null ? null : Timestamp.valueOf(localDateTime); } @Override public LocalDateTime convertToEntityAttribute(Timestamp timestamp) { return timestamp == null ? null : timestamp.toLocalDateTime(); } } ``` 将 LocalDateTime 转换为 JSON 数据: ```java @RestController public class UserController { @GetMapping("/users") public List<User> getUsers() { List<User> users = new ArrayList<>(); users.add(new User(1L, "Tom", LocalDateTime.of(2021, 8, 1, 12, 0, 0))); users.add(new User(2L, "Jerry", LocalDateTime.of(2021, 8, 2, 12, 0, 0))); return users; } @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @GetMapping("/users/{id}") public User getUser(@PathVariable Long id) { return new User(id, "Tom", LocalDateTime.of(2021, 8, 1, 12, 0, 0)); } // 自定义 JsonSerializer 和 JsonDeserializer @GetMapping("/users/{id}/detail") public UserDetail getUserDetail(@PathVariable Long id) { return new UserDetail(id, "Tom", LocalDateTime.of(2021, 8, 1, 12, 0, 0)); } public static class UserDetail { private Long id; private String name; @JsonDeserialize(using = LocalDateTimeDeserializer.class) @JsonSerialize(using = LocalDateTimeSerializer.class) private LocalDateTime createTime; // getter 和 setter } public static class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> { @Override public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { String str = p.getText(); return LocalDateTime.parse(str, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); } } public static class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> { @Override public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeString(value.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值