String to LocalDate

clankill3r picture clankill3r · Jan 5, 2012 · Viewed 192.1k times · Source

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

Answer

hertzi picture hertzi · Mar 20, 2014

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.