How to Format LocalDateTime in Java 8


In Java 8 and later, you can use the DateTimeFormatter class to format a LocalDateTime object. Here’s an example of how to format a LocalDateTime object using DateTimeFormatter:

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

public class LocalDateTimeExample {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
        String formattedDate = now.format(formatter);
        System.out.println(formattedDate);
    }
}

In this example, we create a LocalDateTime object using the now() method, which returns the current date and time. We then create a DateTimeFormatter object using the ofPattern() method, which takes a pattern string to specify the format of the output. In this case, the pattern is “dd/MM/yyyy HH:mm:ss”, which means we want the date in day/month/year format followed by the time in hour:minute:second format.

Finally, we call the format() method on the LocalDateTime object, passing in the DateTimeFormatter object as an argument. This returns a formatted string that represents the date and time in the specified format, which we then print to the console.

The output of the above code might look something like this:

06/05/2022 16:20:30

This is just one example of how to format a LocalDateTime object in Java 8 using DateTimeFormatter. There are many different formatting options and patterns available, so be sure to check the Java documentation for more information.