In Java 8, how can I convert a Timestamp
(in java.sql
) to a LocalDate
(in java.time
)?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You can do:
timeStamp.toLocalDateTime().toLocalDate();
回答2:
I'll slightly expand @assylias answer to take time zone into account. There are at least two ways to get LocalDateTime for specific time zone.
You can use setDefault time zone for whole application. It should be called before any timestamp -> java.time conversion:
public static void main(String... args) {
TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
TimeZone.setDefault(utcTimeZone);
...
timestamp.toLocalDateTime().toLocalDate();
}
Or you can use toInstant.atZone chain:
timestamp.toInstant()
.atZone(ZoneId.of("UTC"))
.toLocalDate();