Java examples to convert from LocalTime
to java.sql.Time
and vice versa.
Note that the Time
class adds formatting and parsing operations to support the JDBC escape syntax for time values. Its date components should be set to the “zero epoch” and should not be accessed.
1. Convert LocalTime to java.sql.Time
Use java.sql.Time.valueOf()
method to get SQL time from LocalTime
instance. Such time instance contains the same hour, minute and second-time value as localtime.
The nanosecond field from LocalTime
is not part of the newly created Time
object.
LocalTime now = LocalTime.now();
Time time = Time.valueOf( now );
System.out.println(time); //13:54:20
2. java.sql.Time to LocalTime
Use java.sql.Time.toLocalTime()
method to get LocalTime
with the same hour, minute, and second-time value as this Time
. The nanosecond LocalTime
field will be set to zero.
//Get SQL time instance
java.sql.Time sqlTime = new Time(new Date().getTime());
//Get LocalTime from SQL time
LocalTime localTime = sqlTime.toLocalTime();
System.out.println( localTime ); //14:00:33
Happy Learning !!
Leave a Reply