Java Convert String to LocalTime

Tags: String Java LocalTime Java 8 DateTimeFormatter

In this Java core tutorial we learn how to convert a String value to a java.time.LocalTime object in Java programming language with different solutions and example Java codes.

Table of contents

  1. How to convert String to LocalTime in Java
  2. How to convert String to LocalTime with custom time format

How to convert String to LocalTime in Java

In Java, we can use the LocalTime.parse(CharSequence text) static method to convert a String in ISO-8601 extended local time format to a LocalTime object as the example Java code below.

ConvertStringToLocalTimeExample1.java

import java.time.LocalTime;

public class ConvertStringToLocalTimeExample1 {
    public static void main(String... args) {
        LocalTime localTime1 = LocalTime.parse("14:40:55.666555444");
        LocalTime localTime2 = LocalTime.parse("14:40:55");

        System.out.println("localTime1: " + localTime1);
        System.out.println("localTime2: " + localTime2);
    }
}
The output as below.
localTime1: 14:40:55.666555444
localTime2: 14:40:55

How to convert String to LocalTime with custom time format

Using the LocalTime.parse(CharSequence text, DateTimeFormatter formatter) method we can convert a time String in specified format to LocalTime object as following example Java code.

ConvertStringToLocalTimeExample2.java

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

public class ConvertStringToLocalTimeExample2 {
    public static void main(String... args) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH-mm-ss-SSSSSSSSS");

        LocalTime localTime = LocalTime.parse("14-40-55-666555444", dateTimeFormatter);

        System.out.println(localTime);
    }
}
The output as below.
14:40:55.666555444

Happy Coding 😊

Java Convert String to LocalDateTime

Java Convert String to LocalDate

Java Convert Date to ZonedDateTime

Java Convert Date to LocalDateTime

Java Convert Date to LocalTime

Java Convert Calendar to LocalDateTime

Java Convert Calendar to ZonedDateTime

Java Convert Calendar to LocalTime