Convert LocalTime to String in Java

This example shows how to convert LocalTime to String in Java.

The java.time.LocalTime class is an immutable class which represents a time without time-zone information.

Read more about LocalTime class with an example at https://www.javaguides.net/2018/08/java-8-localtime-class-api-guide.html.

Convert LocalTime to String in Java

LocalTime class provides below API to convert the LocalTime to String in Java.
  • String format(DateTimeFormatter formatter) - Formats this time using the specified formatter.
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * Program to demonstrate LocalTime Class APIs.
 * @author javaguides.net
 *
 */
public class LocalTimeExample {
 
    public static void main(String[] args) {
        convertLocalTimeToString();
    }

    private static void convertLocalTimeToString(){
        LocalTime localTime = LocalTime.now();

       // ISO Format
       DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_LOCAL_TIME;
       System.out.println(localTime.format(timeFormatter));

       // hour-of-day (0-23)
       DateTimeFormatter timeFormatter1 = DateTimeFormatter
             .ofPattern("HH:mm:ss");
       System.out.println(localTime.format(timeFormatter1));

       // clock-hour-of-am-pm (1-24)
       DateTimeFormatter timeFormatter2 = DateTimeFormatter
             .ofPattern("kk:mm:ss");
       System.out.println(localTime.format(timeFormatter2));

       // clock-hour-of-am-pm (1-12)
       DateTimeFormatter timeFormatter3 = DateTimeFormatter
             .ofPattern("hh:mm:ss a");
       System.out.println(localTime.format(timeFormatter3));

       // hour-of-am-pm (0-11)
       DateTimeFormatter timeFormatter4 = DateTimeFormatter
             .ofPattern("KK:mm:ss a");
       System.out.println(localTime.format(timeFormatter4));
    }
}
Output:
17:47:10.932
17:47:10
17:47:10
05:47:10 PM
05:47:10 PM

Reference

Comments