In this lesson, you will learn to convert String to LocalDate and LocalDateTime objects.
LocalDate and LocalDateTime are immutable date-time objects representing a date and a date and time. To convert String to one of the two Date objects, the provided String must represent a valid date or time according to ISO_LOCAL_DATE or ISO_LOCAL_DATE_TIME. Otherwise, a DateTimeParseException will be thrown.
For more information on Java exception handling, check out this tutorial: Exception Handling in Java.
Convert String to the LocalDate in Java
In this example, we use the parse() method of the LocalDate class to parse the provided String.
import java.time.LocalDate;
class Test {
  public static void main(String[] args) {
    LocalDate date = LocalDate.parse("2021-08-20");
    System.out.println(date.toString());
  }
}
Example
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
class Test {
  public static void main(String[] args) {
    String stringDate = "August 20, 2021";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);
    LocalDate dateTime = LocalDate.parse(stringDate, formatter);
    System.out.println(dateTime.toString());
  }
}
Parse String to the LocalDateTime in Java
Here, we use the parse() method of the LocalDateTime class to convert the provided String to LocalDateTime.
import java.time.LocalDateTime;
class Test {
  public static void main(String[] args) {
    LocalDateTime dateTime = LocalDateTime.parse("2021-08-20T09:50:52");
    System.out.println(dateTime.toString());
  }
}
Example
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
class Test {
  public static void main(String[] args) {
    String dateTimeString = "2018-05-05 11:50:55";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    LocalDateTime localDateTime = LocalDateTime.parse(dateTimeString, formatter);
    System.out.println(localDateTime.toString());
  }
}