Java format LocalTime value to String
Tags: LocalTime LocalTime format DateTimeFormatter DateTimeFormatter ofPattern
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);
}
}
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);
}
}
12:40:03 AM
Happy Coding 😊