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

前端 未结 3 654
后悔当初
后悔当初 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:48

    The accepted answer is not ideal, so I decided to add my 2 cents

    timeStamp.toLocalDateTime().toLocalDate();
    

    is a bad solution in general, I'm not even sure why they added this method to the JDK as it makes things really confusing by doing an implicit conversion using the system timezone. Usually when using only java8 date classes the programmer is forced to specify a timezone which is a good thing.

    The good solution is

    timestamp.toInstant().atZone(zoneId).toLocalDate()
    

    Where zoneId is the timezone you want to use which is typically either ZoneId.systemDefault() if you want to use your system timezone or some hardcoded timezone like ZoneOffset.UTC

    The general approach should be

    1. Break free to the new java8 date classes using a class that is directly related, e.g. in our case java.time.Instant is directly related to java.sql.Timestamp, i.e. no timezone conversions are needed between them.
    2. Use the well-designed methods in this java8 class to do the right thing. In our case atZone(zoneId) made it explicit that we are doing a conversion and using a particular timezone for it.

提交回复
热议问题