postgresql - 如何使用休眠 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 中显示。有人能帮我解决日期问题吗?
解决方案
如果我理解正确的话,通过使用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中呢?:
推荐阅读
- scala - 如何在 Scala LocalDateTime 上将 unix 纪元纳秒仅转换为日期(无时间)
- google-apps-script - 如何使用谷歌应用脚本自定义谷歌表格中的堆栈条形图样式
- ios - iOS 应用:在 AppStore 中被外部测试人员拒绝
- python - 如何在 keras fit_generator() 中定义 max_queue_size、workers 和 use_multiprocessing?
- c++ - Cannot Obtain Similar DL Prediction Result in Pytorch C++ API Compared to Python
- eclipse - 如何解决 jubula autagent“autagent 意外退出”的 mac'os 问题?
- html - 实现实时背景
- api - Twitter API 标准搜索:我可以获得隐藏的回复吗?
- python - 在 Docker 中的 Ubuntu 上使用 azure.storage.blob.BlockBlobService 运行 python 脚本时没有名为“_cffi_backend”的模块
- sql-server - How to get count of number of days left in month from given date