A LocalDate represents a date without time and timezone information. This class was introduced in Java 8 new date and time API for handling dates in ISO-8601 format (yyyy-MM-dd). Unlike legacy Date class, it doesn't store any time or timezone. Instead, it is a description of the date as used for birthdays and anniversaries.

In this quick article, you'll learn how to convert a date string to an instance of LocalDate in Java 8 and higher. The new date and time API provides the parse() method for parsing a string to date. By default, this method accepts a date string in ISO-8601 format — ISO_LOCAL_DATE and parses it directly to an instance of LocalDate.

The following example demonstrates how you can convert the default ISO-8601 formatted string to LocalDate using parse():

// default ISO-8601 formatted string
String str = "2017-06-25";

// parse string to `LocalDate`
LocalDate date = LocalDate.parse(str);

// print `LocalDate`
System.out.println("Parsed LocalDate: " + date);

Here is how the output looks like:

Parsed LocalDate: 2017-06-25

To parse a date string that is not ISO-8601 formatted, you need to pass an instance of DateTimeFormatter to explicitly specify the date string pattern as shown below:

// parse custom date strings
LocalDate date = LocalDate.parse("December 15, 2019", DateTimeFormatter.ofPattern("MMMM dd, yyyy"));
LocalDate date2 = LocalDate.parse("07/17/2019", DateTimeFormatter.ofPattern("MM/dd/yyyy"));
LocalDate date3 = LocalDate.parse("02-Aug-1989", DateTimeFormatter.ofPattern("dd-MMM-yyyy"));

// print `LocalDate` instances
System.out.println(date);
System.out.println(date2);
System.out.println(date3);

The above code snippet will print the following on the console:

2019-12-15
2019-07-17
1989-08-02

Check out How to convert a string to date in Java guide for more string to date conversion examples.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also Subscribe to RSS Feed.

Last Updated: