我们使用 PO 类来表示 sql DB 并使用 Java JPA 实体。在该类中,我们有一列作为字段 currentTime
,其中包含 Timestamp 数据类型和 @version
来自 JPA 的注释。
@Version
private Timestamp currentTime;
每当实体更新时,currentTime 都会更新为最新时间。
currentTime = new Timestamp(0); //this will create the new timestamp with current time.
但目前正在从服务器获取时间。我想在将其保存到数据库之前将其转换为 UTC 格式。
有人可以帮助我如何将时间转换为 UTC 时间吗?
最佳答案
当我需要解析服务器的时间时,我遇到了类似的问题,但我需要先将此时间转换为 UTC 格式,然后再将此信息存储到 MySQL DB 中。这是我的解决方案:
Instant dateConverted = LocalDateTime
.parse(dateTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH))
.atZone(ZoneId.of("Europe/Bratislava")).toInstant();
long epochTime = dateConverted.toEpochMilli() / 1000L;
其中dateTime是一个字符串变量,其中包含服务器的日期和时间 我已经使用 DateTimeFormatter 将时间格式化为适当的格式。 最后,我添加了时区的 zoneID 并将其转换为即时
最后我已经转换为秒
关于java - 我们如何将Java中的时间戳数据类型转换为JPA实体Java中的UTC时区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59782143/