Joda-Time – How to Parse a String to Joda LocalDate

Parsing a string into a Joda-Time LocalDate object is easy. It took me a while to realize that LocalDate has a constructor which can take a date String. Example usage:
LocalDate date = LocalDate.parse("2015-02-28");
The constructor’s signature is actually LocalDate(Object instant), which is why many people don’t realize it can take a Date String! But if you read the API docs, you will see that it says:
The recognised object types are defined in ConverterManager and include ReadablePartial, ReadableInstant, String, Calendar and Date. The String formats are described by ISODateTimeFormat.localDateParser(). The default String converter ignores the zone and only parses the field values.
Then if you read the API docs for ISODateTimeFormat, you will see that the String can be in the following formats:
date-element      = std-date-element | ord-date-element | week-date-element
 std-date-element  = yyyy ['-' MM ['-' dd]]
 ord-date-element  = yyyy ['-' DDD]
 week-date-element = xxxx '-W' ww ['-' e]
Our example above matched that format, so it worked. But what if you need to convert a String in a different format to a LocalDate? Enter DateTimeFormat. Consider the following example:
LocalDate date = LocalDate.parse("6/25/2015", 
                      DateTimeFormat.forPattern("MM/dd/yyyy"));
Also, just to be thorough. LocalDate provides a convenient way to convert back to a String. Its toString method can take a format String:
date.toString();             // returns 2015-06-25
date.toString("MM/dd/yyyy"); // returns 06/25/2015
The methods described in this post also work for LocalDateTime:
LocalDateTime dt1 = LocalDateTime.parse("2013-03-30T09:04:56.123");
LocalDateTime dt2 = LocalDateTime.parse("3/30/2013T0900", 
                      DateTimeFormat.forPattern("MM/dd/yyyy'T'HHmm"));
And then:
dt1.toString("MM/dd/yyyy HH:mm:ss.SSS"); // returns 03/30/2013 09:04:56.123
dt2.toString("MM-dd-yyyy'T'HH:mm:ss");   // returns 03-30-2013T09:00:00
Have fun!
Tagged with:
Posted in Java
Follow Me
RSS FeedFollow me on Twitter
Sponsored
Categories