Postgres UTC到Java ZonedDateTime

关于我原始问题的后续问题 。

因为我知道所使用的任何日期时间都是针对已知的时区,而不是用户可能提交请求的时间,我会使用LocalDateTime,转换为UTC并保留。 然后,当检索到约会时,我将保存的时间转换为会议位置时区(存储在db中)。 但是,我保存的值似乎实际上保存在我当地的时区中。

我在Rest Controller中收到日期时间值,例如:

startLocalDateTime: 2016-04-11T10:00 endLocalDateTime: 2016-04-11T10:30 

约会有两个ZoneDateTime字段:

 @Column(name = "startDateTime", columnDefinition= "TIMESTAMP WITH TIME ZONE") private ZonedDateTime startDateTime; @Column(name = "endDateTime", columnDefinition= "TIMESTAMP WITH TIME ZONE") private ZonedDateTime endDateTime; 

然后我将值更改为UTC并存储在我的实体上以存储到Postgres:

 appointment.setStartDateTime(startLocalDateTime.atZone(ZoneId.of( "UTC" ))) appointment.setEndDateTime(endLocalDateTime.atZone(ZoneId.of( "UTC" ))) 

我将它存储在Postgres中(columnDefinition= "TIMESTAMP WITH TIME ZONE")当我查看pgadminIII中的记录时,我看到:

 startDateTime "2016-04-11 04:00:00-06" endDateTime "2016-04-11 04:30:00-06" 

所以这些似乎以UTC格式正确存储(如果到目前为止我做错了,请纠正我)。 然后我从数据库中检索它们并将它们返回为:

 Appointment startdatetime: 2016-04-11T04:00-06:00[America/Denver] enddatetime: 2016-04-11T04:30-06:00[America/Denver] 

这些值以JSON的forms发回:

 { "appointmentId":50, "startDateTime":"2016-04-11T04:00", "endDateTime":"2016-04-11T04:30" } 

所以,即使我将它们保存为UTC,当我检索它们时,它们处于MST(我的本地)时区,而不是UTC,我无法将它们转换回实际时间。

仍然在坚持不懈。 我尝试在我的实体上使用java.sql.timestamp,java.sql.Date,java.util.Date和java.time.ZonedDateTime。 我的Postgres仍然是“带时区的时间戳”。 但是因为我使用Spring-Data-JPA并且需要使用相同的类型进行查询。 如果我使用Date – 应该是sql.Date还是util.Date?

jdbc驱动程序对你当前所在的时区有一些了解。一般来说,我在数据库为我做时区转换时已经解决了这个问题,一些衍生的“时间戳没有时区AT TIME ZONE区域”或“时间戳”时区“UTC”时区。 它是postgres jdbc驱动程序的核心,它正在计算JVM所处的时区并在保存中使用它。