To convert date-time to time in Java, we can use the toLocalTime() method of the LocalDateTIme class.
This method was added to the java 1.8 date-time API. So, we can use it in Java 8 and higher versions such as Java 11, Java 17, etc.
The toLocalTime() method returns an object of LocalTime class after truncating the date part from the date-time object.
For example, if you want to get time from the date-time "2022-03-14T17:28:13.048999208", then the result will be "17:28:13.048999208".
Let's see the running examples.
/*
* Code example to convert date-time to time object in Java
*/
import java.time.LocalDateTime;
import java.time.LocalTime;
public class JExercise {
public static void main(String[] args) {
// Getting a random date time
LocalDateTime datetime = LocalDateTime.parse("2022-03-14T17:28:13.048999208");
// Displaying date and time
System.out.println("Date Time: "+datetime);
// Get time only
LocalTime time = datetime.toLocalTime();
// Display result
System.out.println("Time: "+time);
}
}
Output:
Date Time: 2022-03-14T17:28:13.048999208
Time: 17:28:13.048999208
Now, let's see its singature
public LocalTime toLocalTime()
Package Name: java.time;
Class Name: LocalDateTime
Return Value: It returns the LocalTime object with the same time, not null.
Parameters: No
Version: Since 1.8
Let's see some more examples.
We can use the toLocalTime() method to get the current time from date-time as well.
Here, first, we used the now() method to get the current date-time and then used the toLocalTime() method to get the current time.
/*
* Code example to convert date-time to time object in Java
*/
import java.time.LocalDateTime;
import java.time.LocalTime;
public class JExercise {
public static void main(String[] args) {
// Getting the current date time
LocalDateTime datetime = LocalDateTime.now();
// Displaying date and time
System.out.println("Date Time: "+datetime);
// Get current time only
LocalTime time = datetime.toLocalTime();
// Display result
System.out.println("Time: "+time);
}
}
Output:
Date Time: 2022-07-14T21:48:28.251627300
Time: 21:48:28.251627300
Use this code to get results in a single line of code. If you are a beginner, skip this code.
LocalDateTime.now().toLocalTime()
This code will return the current LocalTime object from the LocalDateTime after truncating the date part. You just need to put this into your code and get the result instantly.