java - JDBC result set retrieve LocalDateTime - Stack Overflow
java - JDBC result set retrieve LocalDateTime - Stack Overflow
Asked 5 years, 6 months ago Modified 4 years, 4 months ago Viewed 24k times
I run a simple query to retrieve a row from a MySQL database. I get ResultSet and I need to
retrieve a LocalDateTime object from it. My DB table.
Share Improve this question edited Oct 3, 2019 at 17:28 asked Aug 1, 2018 at 11:59
Follow Yan Khonski
12.6k 16 79 114
this might help Parse DateTime to LocalDateTime from resulset – Ramon jansen gomez Aug 1, 2018 at
12:03
Yes, I see. 1) Retrieve timestamp from the resultSet, 2) convert it into LocalDateTime... – Yan Khonski
Aug 1, 2018 at 12:13
13 If the JDBC driver is reasonably current and has been updated to work with Java 8 then you should be
able to use resultSet.getObject(4, LocalDateTime.class) – Gord Thompson Aug 1, 2018 at
13:13
EDIT: As Gord Thompson pointed out in his comment, there's an even better solution when
working with a recent enough JDBC driver:
resultSet.getObject(4, LocalDateTime.class)
Share Improve this answer Follow edited Aug 1, 2018 at 13:22 answered Aug 1, 2018 at 12:05
Tomasz Linkowski
4,426 25 38
Even if I use DateTime for MySQL, I should call getTimestamp() ? Not getDate() ? – Yan Khonski
Aug 1, 2018 at 12:06
1 java.sql.Date has no time component: "To conform with the definition of SQL DATE , the
millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours,
minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is
associated." I do not guaratee that java.sql.Timestamp will work, though, but it seems to be the
only type that represents date-time in java.sql package. – Tomasz Linkowski Aug 1, 2018 at 12:10
7 +1 for the edit. It also avoids the problem of Timestamp potentially corrupting certain date/time
values, e.g., 2018-03-11 02:00:00 (2 AM) in America/Toronto will magically be changed to 3
AM. – Gord Thompson Aug 1, 2018 at 13:31
resultSet.getObject(4, LocalDateTime.class) using postgres and latest jdbc lib didn't work
for me. resultSet.getTimestamp(4).toLocalDateTime() did work – Tony Murphy Jan 27, 2020
at 20:52
2 I tried this technique recently. However, even though the above code should work, there's a MySQL
driver bug that incorrectly applies a timezone offset to the LocalDateTime value. This bug is still
open as of MySQL Connector Java version 8.0.19. Reference: bugs.mysql.com/bug.php?id=93444
– rdguam May 18, 2020 at 0:04