首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用hibernate Quarkus从postgresql读取“带时区的时间戳”

如何使用hibernate Quarkus从postgresql读取“带时区的时间戳”
EN

Stack Overflow用户
提问于 2021-11-14 20:28:04
回答 1查看 449关注 0票数 0

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

DB类型: postgresql

DB列类型:带有时区的时间戳

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

从DB读取后的值: 2021-11-02T22:16:16.108341-04:00

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

实体:私有OffsetDateTime createdOn;

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

EN

回答 1

Stack Overflow用户

发布于 2021-11-14 21:52:57

如果我对你的理解是正确的,通过使用atZoneSameInstant,你就可以实现你想要的目标:

代码语言:javascript
复制
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]

代码语言:javascript
复制
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

==编辑的==

如果希望数据库将信息存储在(区域)中,但在UI (UTC)中,则需要自定义方法。

代码语言:javascript
复制
@Entity
public class YourEntity{

 private OffsetDateTime createdOn;

 public ZonedDateTime getTimeInUTC{

  return //convert createdOn;

}

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

How to store date/time and timestamps in UTC time zone with JPA and Hibernate

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69966905

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档