Java Convert LocalTime to LocalDateTime
Tags: Java LocalTime Java LocalDateTime Java 8
In this Java core tutorial we learn how to convert a java.time.LocaTime object with a given java.time.LocalDate value into a java.time.LocalDateTime object.
How to convert LocalTime to LocalDateTime in Java
With a given LocalTime object in Java, we can combine with a specified LocalDate object to create a LocalDateTime object by using the LocalTime.atDate(). The following Java program to show how to use the LocalTime.atDate() method to convert LocalTime object with current date of system to LocalDateTime object.
ConvertLocalTimeToLocalDateTimeExample1.java
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class ConvertLocalTimeToLocalDateTimeExample1 {
public static void main(String... args) {
int hour = 1;
int minute = 10;
int second = 20;
LocalTime localTime = LocalTime.of(hour, minute, second);
LocalDate today = LocalDate.now();
LocalDateTime localDateTime = localTime.atDate(today);
System.out.println("LocalTime: " + localTime);
System.out.println("LocalDateTime: " + localDateTime);
}
}
LocalTime: 01:10:20
LocalDateTime: 2022-04-21T01:10:20
In the following Java code we show how to combined LocalTime object with a specified LocalDate object to create new LocalDateTime object.
ConvertLocalTimeToLocalDateTimeExample2.java
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class ConvertLocalTimeToLocalDateTimeExample2 {
public static void main(String... args) {
int hour = 1;
int minute = 10;
int second = 20;
int year = 2022;
int month = 1;
int day = 1;
LocalDate localDate = LocalDate.of(year, month, day);
LocalTime localTime = LocalTime.of(hour, minute, second);
LocalDateTime localDateTime = localTime.atDate(localDate);
System.out.println("LocalDate: " + localDate);
System.out.println("LocalTime: " + localTime);
System.out.println("LocalDateTime: " + localDateTime);
}
}
LocalDate: 2022-01-01
LocalTime: 01:10:20
LocalDateTime: 2022-01-01T01:10:20
Happy Coding 😊
Related Articles
Java Convert LocalTime to String
Java Convert LocalTime to Seconds of Day
Java Convert LocalTime to Nanos of Day
Java Convert LocalTime to Epoch Seconds
Java Convert LocalTime to OffsetTime
Java Convert LocalTime to Date
Java Convert LocalTime to Calendar