PostgreSQL timestamptz 映射 Java OffsetDateTime 注意点
PostgreSQL Java 时区 About 1,284 words特别注意
如果直接将从PostgreSQL
中映射过来的OffsetDateTime
字段,如转为LocalDateTime
需要特别注意。
OffsetDateTime offsetDateTime = OffsetDateTime.now(ZoneOffset.UTC);
System.out.println("offsetDateTime: " + offsetDateTime);
LocalDateTime localDateTime = OffsetDateTime.now(ZoneOffset.UTC).toLocalDateTime();
System.out.println("localDateTime: " + localDateTime);
输出
offsetDateTime: 2024-07-01T08:05:58.675885Z
localDateTime: 2024-07-01T08:05:58.676026
可以看到:PostgreSQL
中映射过来的OffsetDateTime
是零时区的时间字段。转为LocalDateTime
时会直接丢掉时区信息。
原因:PostgreSQL
底层存储的就是零时区的timestamptz
。
Note
ZonedDateTime , Instant and OffsetTime / TIME WITH TIME ZONE are not supported. Also note that all OffsetDateTime instances will have be in UTC (have offset 0). This is because the backend stores them as UTC.
参考:https://jdbc.postgresql.org/documentation/query/#table51-supportedjava-8-date-and-time-classes
常用处理方法
timestamptz
使用String
、java.util.Date
、java.sql.Timestamp
接收- 将
OffsetDateTime
转为Date
类型 - 先将
OffsetDateTime
转为秒级时间戳,再用该时间戳转为LocalDateTime
PostgreSQL 接收 timestamptz
{
"timeStr": "2024-07-01 15:52:17.399315+08",
"timeOffsetDateTime": "2024-07-01T07:52:17.399315Z",
"timeDate": "2024-07-01T07:52:17.399+00:00",
"timeTimestamp": "2024-07-01T07:52:17.399+00:00"
}
相关文档
Views: 667 · Posted: 2024-07-01
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...