How to convert java.sql.timestamp to LocalDate (java8) java.time?

前端 未结 3 653
后悔当初
后悔当初 2020-12-23 20:12

In Java 8, how can I convert a Timestamp (in java.sql) to a LocalDate (in java.time)?

3条回答
  •  醉话见心
    2020-12-23 20:39

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

提交回复
热议问题