How to convert java.sql.timestamp to LocalDate (ja

2019-01-31 11:32发布

问题:

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();