Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to LocalDate

Tags:

java

jodatime

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 
like image 496
clankill3r Avatar asked Jan 05 '12 16:01

clankill3r


People also ask

How do I cast a string to LocalDate?

Parsing String to LocalDateparse() 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.

How convert string from YYYY-MM-DD to LocalDate in Java?

Use MM that represents Month instead of mm that represents minutes. Use LocalDate. parse() instead of new LocalDate() to construct the LocalDate object.

What method is used to create a new LocalDate from a string?

Use LocalDate. format(DateTimeFormatter) method to format a local date to the desired string representation.


1 Answers

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.

like image 164
hertzi Avatar answered Oct 16 '22 09:10

hertzi