Java LocalDateTime from LocalDate and LocalTime



Write a Java 8 program that builds a LocalDateTime from LocalDate and LocalTime. Combine date and time in a single LocalDateTime object.

Java LocalDateTime from LocalDate and LocalTime


import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class Main {

    public static void main(String[] args) {
                       
        LocalDate localDate = LocalDate.now();
        String localDateAsString = localDate
                .format(DateTimeFormatter.ofPattern("yyyy-MMM-dd"));
        System.out.println("LocalDate: " + localDateAsString);
        
        LocalTime localTime = LocalTime.now();
        String localTimeAsString = localTime
                .format(DateTimeFormatter.ofPattern("hh:mm:ss a"));
        System.out.println("LocalTime: " + localTimeAsString);
        
        LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);
        
        String localDateTimeAsString = localDateTime
                .format(DateTimeFormatter.ofPattern("yyyy-MMM-dd hh:mm:ss a"));
        
        System.out.println("LocalDateTime: " + localDateTimeAsString);
    }
    
}

Output:

LocalDate: 2021-Nov-10
LocalTime: 06:11:27 pm
LocalDateTime: 2021-Nov-10 06:11:27 pm

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course

Comments