我正面临显示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中显示。有人能帮我解决日期问题吗?
发布于 2021-11-14 21:52:57
如果我对你的理解是正确的,通过使用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

==编辑的==
如果希望数据库将信息存储在(区域)中,但在UI (UTC)中,则需要自定义方法。
@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
https://stackoverflow.com/questions/69966905
复制相似问题