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.
1.1. Default Pattern
The following program converts a String to LocalDate where the date string is in default format yyyy-MM-dd
.
LocalDate today = LocalDate.parse("2019-03-29");
1.2. Custom Pattern
In the following program, we convert a date string in the custom pattern dd-MMM-yyyy to a LocalDate instance.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
LocalDate date = LocalDate.parse("29-Mar-2019", formatter);
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 to 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 strings 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 !!