Convert String to LocalTime in Java

This example shows how to convert String to LocalTime object 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 String to LocalTime in Java

LocalTime class provides below APIs to convert String to LocalTime in java.
  • static LocalTime parse(CharSequence text) - Obtains an instance of LocalTime from a text string such as 10:15.
  • static LocalTime parse(CharSequence text, DateTimeFormatter formatter) - Obtains an instance of LocalTime from a text string using a specific formatter.
In the below example, we are passing string text such as "10:15:30", "10:45:30 PM", etc and converted into LocalTime object:
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) {
        convertStringToLocalTime();
    }

    private static void convertStringToLocalTime() {
        LocalTime isoTime = LocalTime.parse("10:15:30", DateTimeFormatter.ISO_LOCAL_TIME);
        System.out.println(isoTime);

        // hour-of-day (0-23)
        LocalTime localTime = LocalTime.parse("22:45:30", DateTimeFormatter.ofPattern("HH:mm:ss"));
        System.out.println(localTime);

        // clock-hour-of-am-pm (1-24)
        LocalTime localTime2 = LocalTime.parse("22:45:30", DateTimeFormatter.ofPattern("kk:mm:ss"));
        System.out.println(localTime2);

        // clock-hour-of-am-pm (1-12)
        LocalTime localTime3 = LocalTime.parse("10:45:30 PM", DateTimeFormatter.ofPattern("hh:mm:ss a"));
        System.out.println(localTime3);

        // hour-of-am-pm (0-11)
        LocalTime localTime4 = LocalTime.parse("10:45:30 AM", DateTimeFormatter.ofPattern("KK:mm:ss a"));
        System.out.println(localTime4);
    }
}
Output:
10:15:30
22:45:30
22:45:30
22:45:30
10:45:30

Reference



Comments