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

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

+112
java timestamp java-8 java-time localtime
Apr 24 '14 at 8:17
source share
3 answers

You can do:

 timeStamp.toLocalDateTime().toLocalDate(); 
+176
Apr 24 '14 at 9:07
source share
— -

I will expand @assylias answer a bit to take into account the time zone. There are at least two ways to get LocalDateTime for a specific time zone.

You can use setDefault timezone for the whole application. It must be called before any timestamp -> java.time:

 public static void main(String... args) { TimeZone utcTimeZone = TimeZone.getTimeZone("UTC"); TimeZone.setDefault(utcTimeZone); ... timestamp.toLocalDateTime().toLocalDate(); } 

Or you can use the toInstant.atZone chain:

 timestamp.toInstant() .atZone(ZoneId.of("UTC")) .toLocalDate(); 
+7
Jun 26 '18 at 14:21
source share

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

 timeStamp.toLocalDateTime().toLocalDate(); 

this is a bad decision in general , I'm not even sure why they added this method to the JDK, since it makes things really confusing, making an implicit conversion using the system time zone. Usually, when only java8 date classes are used, the programmer is forced to specify the time zone, which is good.

Good decision -

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

Where zoneId is the time zone you want to use. This is usually ZoneId.systemDefault () if you want to use the system time zone or some hard-coded time zone, such as ZoneOffset..UTC

The general approach should be

  1. Get rid of the new java8 date classes using a class that has a direct relationship, for example, in our case, java.time.Instant is directly related to java.sql.Timestamp , i.e. Converting time zones between them is not required.
  2. Use properly designed methods in this java8 class to do the right thing. In our case, atZone (zoneId) directly indicated that we are doing the conversion and use a specific time zone for it.
+7
Jul 18 '19 at 19:35
source share



All Articles