Java format LocalTime value to String

In this Java core tutorial we learn how to format a LocalTime value to formatted String using the DateTimeFormatter class.

How to format time using DateTimeFormatter in Java

FormatLocalTimeExample1.java

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

public class FormatLocalTimeExample1 {
    public static void main(String... args) {
        LocalTime localTime = LocalTime.now();

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        String formattedTime = localTime.format(dateTimeFormatter);

        System.out.println(formattedTime);
    }
}
The output is:
00:39:50

FormatLocalTimeExample2.java

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

public class FormatLocalTimeExample2 {
    public static void main(String... args) {
        LocalTime localTime = LocalTime.now();

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("hh:mm:ss a");
        String formattedTime = localTime.format(dateTimeFormatter);

        System.out.println(formattedTime);
    }
}
The output is:
12:40:03 AM

Happy Coding 😊