[java] String to LocalDate

How can i convert a string to a LocalDate?

I have seen examples like:

LocalDate dt = new LocalDate("2005-11-12");

But my strings are like:

2005-nov-12

This question is related to java jodatime

The answer is


DateTimeFormatter has in-built formats that can directly be used to parse a character sequence. It is case Sensitive, Nov will work however nov and NOV wont work:

DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MMM-dd");

try {
    LocalDate datetime = LocalDate.parse(oldDate, pattern);
    System.out.println(datetime); 
} catch (DateTimeParseException e) {
    // DateTimeParseException - Text '2019-nov-12' could not be parsed at index 5
    // Exception handling message/mechanism/logging as per company standard
}

DateTimeFormatterBuilder provides custom way to create a formatter. It is Case Insensitive, Nov , nov and NOV will be treated as same.

DateTimeFormatter f = new DateTimeFormatterBuilder().parseCaseInsensitive()
        .append(DateTimeFormatter.ofPattern("yyyy-MMM-dd")).toFormatter();
try {
    LocalDate datetime = LocalDate.parse(oldDate, f);
    System.out.println(datetime); // 2019-11-12
} catch (DateTimeParseException e) {
     // Exception handling message/mechanism/logging as per company standard
}

java.time

Since Java 1.8, you can achieve this without an extra library by using the java.time classes. See Tutorial.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd");
formatter = formatter.withLocale( putAppropriateLocaleHere );  // Locale specifies human language for translating, and cultural norms for lowercase/uppercase and abbreviations and such. Example: Locale.US or Locale.CANADA_FRENCH
LocalDate date = LocalDate.parse("2005-nov-12", formatter);

The syntax is nearly the same though.


You may have to go from DateTime to LocalDate.

Using Joda Time:

DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("yyyy-MMM-dd");
DateTime dateTime = FORMATTER.parseDateTime("2005-nov-12");
LocalDate localDate = dateTime.toLocalDate();

Datetime formatting is performed by the org.joda.time.format.DateTimeFormatter class. Three classes provide factory methods to create formatters, and this is one. The others are ISODateTimeFormat and DateTimeFormatterBuilder.

DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MMM-dd");
LocalDate lDate = new LocalDate().parse("2005-nov-12",format);

final org.joda.time.LocalDate class is an immutable datetime class representing a date without a time zone. LocalDate is thread-safe and immutable, provided that the Chronology is as well. All standard Chronology classes supplied are thread-safe and immutable.