Home > database >  transform java.sql.Date to LocalDateTime
transform java.sql.Date to LocalDateTime

Time:10-21

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.

CodePudding user response:

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

  • Related