Convert String to LocalDate

Java LocalDate class represents a calendar date without time (hour/minute/seconds) and timezone information. Learn to convert a string to LocalDate object in Java.

The default date pattern is DateTimeFormatter.ISO_LOCAL_DATE which is yyyy-MM-dd.

1. Parsing String to LocalDate

The LocalDate.parse() method takes two arguments. The first argument is the string representing the date. And the second optional argument is an instance of DateTimeFormatter specifying any custom pattern.

//Default pattern is yyyy-MM-dd

LocalDate today = LocalDate.parse("2019-03-29");
System.out.println(today);

//Custom pattern is yyyy/MM/dd

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
LocalDate date = LocalDate.parse("29-Mar-2019", formatter);
System.out.println(date);

Program output.

2019-03-29
2019-03-29

2. Locale Specific Patterns

Sometimes we may have dates in specific locales such as french e.g. 29-Mar-2019 will be written in French as 29-Mars-2019. To parse such dates, use DateTimeFormatter withLocale() method ro get the formatter in that locale and parse the dates.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy")
							.withLocale(Locale.FRENCH);

LocalDate date = LocalDate.parse("29-mai-2019", formatter);

System.out.println(date);

Program output.

2019-05-29

3. Useful Date Patterns

Given below are some useful date patterns and their examples for converting dates in string to LocalDate.

Pattern
Example date string
yyyy-MM-dd
2019-03-29
dd-MMM-yyyy
29-Mar-2019
dd/MM/yyyy
29/03/2019
E, MMM dd yyyy
Fri, Mar 29 2019

Happy Learning !!

Sourcecode on Github

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.