gpt4 book ai didi

java - LocalDateTime , ZonedDateTime 和时间戳

转载 作者:IT老高 更新时间:2023-10-29 00:15:33 24 4
gpt4 key购买 nike

我有一个 SpringBoot 应用程序。使用 Spring Initializer、嵌入式 Tomcat、Thymeleaf 模板引擎,并打包为可执行 JAR 文件。

我有一个具有 2 个属性(initDate、endDate)的域对象。我想创建 2 个转换器来处理 mySQL DB

@Convert(converter = LocalDateTimeAttributeConverter.class) 
private LocalDateTime initDate;

@Convert(converter = ZonedDateTimeAttributeConverter.class)
private ZonedDateTime endDate;

转换器1(没问题)

@Converter
public class LocalDateTimeAttributeConverter implements AttributeConverter<LocalDateTime, Timestamp> {

@Override
public Timestamp convertToDatabaseColumn(LocalDateTime localDateTime) {
return (localDateTime == null ? null : Timestamp.valueOf(localDateTime));
}

@Override
public LocalDateTime convertToEntityAttribute(Timestamp sqlTimestamp) {
return (sqlTimestamp == null ? null : sqlTimestamp.toLocalDateTime());
}
}

这是我要创建的一个

@Converter
public class ZonedDateTimeAttributeConverter implements AttributeConverter<ZonedDateTime, Timestamp> {

@Override
public Timestamp convertToDatabaseColumn(ZonedDateTime zoneDateTime) {
return (zoneDateTime == null ? null : Timestamp.valueOf(zoneDateTime));
}


@Override
public ZonedDateTime convertToEntityAttribute(Timestamp sqlTimestamp) {
return (sqlTimestamp == null ? null : sqlTimestamp.toZonedDateTime());
}
}

但我不能,因为我有 2 个错误:

The method valueOf(String) in the type Timestamp is not applicable for the arguments (ZonedDateTime)

并且TimeStamp没有方法toZonedDateTime()

如果我没有为 ZonedDate 添加任何转换器,JPA 会创建一个类型为 varbinary(255)

的表

最佳答案

Timestamp扩展 Date 以提供纳秒精度。 DateTimestamp 都没有设计为将特定时区称为 ZoneDateTime

如果您需要转换 ZonedDateTime -> Timestamp 您将不得不丢弃时区/偏移信息。例如

LocalDateTime withoutTimezone = zoneDateTime.toLocalDateTime();
Timestamp timestamp = Timestamp.valueOf(withoutTimezone));

对于转换 Timestamp -> ZonedDateTime 你需要指定一个偏移量:

LocalDateTime withoutTimezone = sqlTimestamp.toLocalDateTime();
ZonedDateTime withTimezone = withoutTimezone.atZone(ZoneId.of("+03:00"));

或时区:

ZonedDateTime withTimezone = withoutTimezone.atZone(ZoneId.of("Europe/Paris"));

如果您的意图是在数据库中保存 ZonedDateTime 变量并保留在那里指定的各种时区,我建议您相应地设计您的数据库。建议:

  1. 使用 DATETIME 类型的列保存 LocalDateTimeVARCHAR 保存时区,例如 "Europe/Paris"SMALLINT 以分钟为单位保存偏移量。
  2. ZonedDateTime 转换为 String 并保存在 VARCHAR 列中,例如 "2017-05-16T14:12:48.983682 +01:00[欧洲/伦敦]"。然后,您必须在从数据库中读取数据时对其进行解析。

关于java - LocalDateTime , ZonedDateTime 和时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44002104/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com