首页 > 解决方案 > 如何使用休眠 Quarkus 从 postgresql 读取“带时区的时间戳”

问题描述

我面临在 UI 中显示 UTC 日期时间的问题。

数据库类型:postgresql

数据库列类型:带时区的时间戳

DB列值:2021-11-02 22:16:16.108341-04

从 DB 读取值后:2021-11-02 T 22:16:16.108341-04:00

用户界面数据:2021-11-02T22:16:16.108341-04:00

实体:private OffsetDateTime createdOn;

从 UI 我们无法解析 UTC 日期时间值并在 UI 中显示。有人能帮我解决日期问题吗?

标签: postgresqlhibernatequarkus

解决方案


如果我理解正确的话,通过使用atZoneSameInstant你可以实现你所追求的:

OffsetDateTime time = OffsetDateTime.parse("2021-11-02T22:16:16.108341-04:00");

ZonedDateTime timeInUTC = time.atZoneSameInstant(ZoneId.of("UTC"));

System.out.println(timeInUTC);  ///2021-11-03T02:16:16.108341Z[UTC]

atZoneSameInstant

public ZonedDateTime atZoneSameInstant(ZoneId zone)

Combines this date-time with a time-zone to create a ZonedDateTime ensuring that the result has the same instant.

This returns a ZonedDateTime formed from this date-time and the specified time-zone. This conversion will ignore the visible local date-time and use the underlying instant instead. This avoids any problems with local time-line gaps or overlaps. The result might have different values for fields such as hour, minute an even day.

To attempt to retain the values of the fields, use atZoneSimilarLocal(ZoneId). To use the offset as the zone ID, use toZonedDateTime().

Parameters:
    zone - the time-zone to use, not null
Returns:
    the zoned date-time formed from this date-time, not null

在此处输入图像描述

== 已编辑 ==

如果您希望您的数据库将信息存储在(您的 ZONE)中,但在 UI(UTC)中,那么您需要一个自定义方法。

@Entity
public class YourEntity{

 private OffsetDateTime createdOn;

 public ZonedDateTime getTimeInUTC{

  return //convert createdOn;

}

但是,如果您担心转换导致的“成本”,为什么不直接省去麻烦并将hibernate配置为直接存储在UTC中呢?:

如何使用 JPA 和 Hibernate 在 UTC 时区中存储日期/时间和时间戳


推荐阅读