我目前在将
java.sql.Timestamp
转换为 LocalDateTime
时遇到困难。据我所知,Timestamp
(和Date
)不知道任何时区。我有一个代表 UTC 时间的时间戳。我想将此时间戳转换为我的本地时区 (GMT+2)。当我在 #toInstant()
上拨打 Timestamp
时,我得到的约会时间会少 2 小时。我认为这是因为 Instant 代表 UTC 时间尺度上的一个时间点。显然java认为我的时间戳位于我的默认时区(= GMT+2),这就是为什么toInstant()
从原始时间戳中减去两个小时。但是这个 Timestamp
已经代表 UTC 时间,因此从中减去两个小时是错误的。
我尝试了以下方法:
Timestamp stamp = new Timestamp(123, 7, 1, 10, 0, 0, 0); //this represents 2023-08-01 10:00:00 (UTC)
stamp.toInstant() //returns 2023-08-01 08:00:00
我想要的是:2023-08-01 12:00:00 我能够得到结果:
Instant nowUtc = Instant.now();
ZoneId europeZone = ZoneId.of("Europe/Berlin");
ZonedDateTime berlinTime = ZonedDateTime.ofInstant(nowUtc, europeZone);
但是在这个工作解决方案中不涉及时间戳。
试试这个:
static LocalDateTime toZoned(Timestamp ts) {
return ts.toInstant()
.atZone(ZoneOffset.UTC)
.withZoneSameInstant(ZoneId.of("Europe/Berlin"))
.toLocalDateTime();
}