LocalDate parse()

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

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

1. String to LocalDate example – default and custom patterns

Java example to convert a string into LocalDate.

//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. DateTimeFormatter with Locale

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 for conversion

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

PatternExample date string
yyyy-MM-dd2019-03-29
dd-MMM-yyyy29-Mar-2019
dd/MM/yyyy29/03/2019
E, MMM dd yyyyFri, Mar 29 2019
EEEE, MMM dd, yyyy HH:mm:ss aFriday, Mar 29, 2019 12:10:56 PM
DateTimeFormatter.ISO_LOCAL_DATE_TIME2019-03-29T10:15:30
DateTimeFormatter.ISO_INSTANT2019-03-29T10:15:30Z
DateTimeFormatter.ISO_DATE_TIME2019-03-29T10:15:30+08:00

Drop me your questions related to string to localdate conversion in Java 8 – in comments.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.