Java Convert String to LocalDateTime

Tags: String Java LocalDateTime Java 8 DateTimeFormatter

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

Table of contents

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

How to convert String to LocalDateTime in Java

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

ConvertStringToLocalDateTimeExample1.java

import java.time.LocalDateTime;

public class ConvertStringToLocalDateTimeExample1 {
    public static void main(String... args) {
        LocalDateTime localDateTime1 = LocalDateTime.parse("2022-05-19T09:30:50.111222333");
        LocalDateTime localDateTime2 = LocalDateTime.parse("2022-05-19T09:30:50");

        System.out.println("localDateTime1: " + localDateTime1);
        System.out.println("localDateTime2: " + localDateTime2);
    }
}
The output as below.
localDateTime1: 2022-05-19T09:30:50.111222333
localDateTime2: 2022-05-19T09:30:50

How to convert String to LocalDateTime with custom date time format

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

ConvertStringToLocalDateTimeExample2.java

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class ConvertStringToLocalDateTimeExample2 {
    public static void main(String... args) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");

        LocalDateTime localDateTime = LocalDateTime.parse("19/05/2022 09:30:50", dateTimeFormatter);

        System.out.println("localDateTime: " + localDateTime);
    }
}
The output as below.
localDateTime: 2022-05-19T09:30:50

Happy Coding 😊

Java Convert String to LocalTime

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