Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joda time : How to convert String to LocalDate?

Tags:

java

jodatime

How to specify the format string to convert the date alone from string. In my case, only the date part is relevant

Constructing it as DateTime fails:

String dateString = "2009-04-17"; DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd"); DateTime dateTime = formatter.parseDateTime(dateString); 

with error java.lang.IllegalArgumentException: Invalid format: "2011-04-17" is too short

Probably because I should use LocalDate instead. But, I do not see any formatter for LocalDate . What is the best way to convert String dateString = "2009-04-17"; into LocalDate (or something else if that is not the right representation)

thanks...

like image 459
bsr Avatar asked Apr 27 '10 13:04

bsr


People also ask

How do I convert 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.

What is Joda LocalDate?

LocalDate is an immutable datetime class representing a date without a time zone. LocalDate implements the ReadablePartial interface. To do this, the interface methods focus on the key fields - Year, MonthOfYear and DayOfMonth. However, all date fields may in fact be queried.

Is Joda time deprecated?

So the short answer to your question is: YES (deprecated).

What is the replacement of Joda time?

time (JSR-310) which is a core part of the JDK which replaces joda library project.


2 Answers

You're probably looking for LocalDate(Object). It's a bit confusing since it takes a generic Object, but the docs indicate that it will use a ConverterManager that knows how to handle a String if you pass a String to the constructor, e.g.

LocalDate myDate = new LocalDate("2010-04-28"); 
like image 169
Hank Gay Avatar answered Sep 22 '22 13:09

Hank Gay


Use the parse(String) method.

LocalDate date = LocalDate.parse("2009-04-17"); 
like image 20
JodaStephen Avatar answered Sep 18 '22 13:09

JodaStephen