Skip to content
Advertisement

transform java.sql.Date to LocalDateTime

I have a java.sql.Date object and want to transform it to a java.time.LocalDateTime object.

For comparison, I am able to do a similar transformation using java.util.Date:

java.util.Date utilDate = new java.util.Date(sqlDate.getTime());
System.out.println("date with time: " + utilDate);

This answer doesn’t work for me, as my java.sql.Date does not have a getTimestamp method.

For reference, this question addresses the opposite transformation.

Advertisement

Answer

You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310.

  • Do not use java.sql.Date
  • Do not use java.util.Date
  • Do not use java.sql.Timestamp
  • Do not use java.util.Calendar

Use only java.time classes.

For exchanging date-time values with a database, use JDBC 4.2 or later.

The java.sql.Date class pretends to represent a date-only value.

If you are handed a java.sql.Date object, immediately convert it to a java.time.LocalDate. Use the new method toLocalDate added to that old class.

LocalDate localDate  = myJavaSqlDate.toLocalDate() ;

You asked for a java.time.LocalDateTime object. You have the necessary date portion. Now you need to assign the time-of-day portion.

LocalTime localTime = LocalTime.of( 15 , 30 );

Combine.

LocalDateTime localDateTime = LocalDateTime.of( localDate, localTime ) ;

A LocalDateTime is inherently ambiguous. 3:30 PM 🕞 in Japan 🇯🇵 is a different moment than 3:30 PM 🕞 in Morocco 🇲🇦.

To determine a moment, a specific point on the timeline, place your LocalDateTime within the context of a time zone. You get a ZonedDateTimeObject.

ZoneId zoneId = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime zonedDateTime = localDateTime.atZone( zoneId ) ;

To view that moment as seen in UTC, with an offset from UTC of zero hours-minutes-seconds, extract an Instant.

Instant instant = zonedDateTime.toInstant() ;
Advertisement