在Java 8中,我该如何将一个java.sql.Timestamp转换为java.time.LocalDate?
您可以执行以下操作:
timeStamp.toLocalDateTime().toLocalDate();
请注意,timestamp.toLocalDateTime()
将使用Clock.systemDefaultZone()
时区进行转换。这可能是您想要的,也可能不是。timestamp.toLocalDateTime()
方法将使用系统默认时区进行转换。这可能是您想要的,也可能不是。 - jacobhyphenated接受的答案并不理想,因此我决定补充我的意见。
timeStamp.toLocalDateTime().toLocalDate();
一般情况下,这是一个不好的解决方案,我甚至不确定为什么他们要将这个方法添加到JDK中,因为它会使用系统时区进行隐式转换,使事情变得非常混乱。通常,当仅使用java8日期类时,程序员被迫指定时区,这是一件好事。
好的解决方案是
timestamp.toInstant().atZone(zoneId).toLocalDate()
其中zoneId是你想要使用的时区,通常为ZoneId.systemDefault()(如果你想使用系统时区)或一些硬编码的时区,比如ZoneOffset.UTC
一般的做法应该是:
.toLocalDateTime()
再次使用默认时区将毫秒数转换为LocalDateTime。这对我来说似乎相对安全。 - Yay295我会稍微扩展@assylias的回答,考虑到时区的因素。有至少两种方法可以获取特定时区的LocalDateTime。
您可以为整个应用程序设置默认时区。它应该在任何时间戳 -> java.time转换之前调用:
public static void main(String... args) {
TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
TimeZone.setDefault(utcTimeZone);
...
timestamp.toLocalDateTime().toLocalDate();
}
或者您可以使用 toInstant.atZone 链:
timestamp.toInstant()
.atZone(ZoneId.of("UTC"))
.toLocalDate();