1

I'm trying to create a LocalDate object, using the JodaTime library, from an input string. The string comes from a database that I have no control over. The input date of birth looks exactly like this:

1963-07-19T00:00:00.000+0000

I just want the 1963-07-19 portion, I don't want the time portion. So I tried to implement a formatter like so:

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");

And then create the LocalDate object like so:

LocalDate dob = formatter.parseLocalDate(dateOfBirth);

But I get the error:

Invalid format: "1963-07-19T00:00:00.000+0000" is malformed at "T00:00:00.000+0000"

I've also tried a formatter like so:

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'hh:mm:ss.SSSZ");

But then I get the error:

Cannot parse "1963-07-19T00:00:00.000+0000": Value 0 for clockhourOfHalfday must be in the range [1,12]

And idea how to accomplish what I want?

Richard
  • 5,840
  • 36
  • 123
  • 208

2 Answers2

2

Your first example won't work because parseLocalDate has to match the entire input string against your pattern.

For your second example, according to the javadoc of DateTimeFormat, the pattern letter h defines

h       clockhour of halfday (1~12)  number        12

It looks like you want

H       hour of day (0~23)           number        0
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • Perfect, this worked. I'm just worried the DB will spit back something weirder later on and crash the prog. Fingers crossed. – Richard Dec 17 '15 at 21:03
  • @richard If you need to, jodatime allows you to define multiple parsers. See [here](http://stackoverflow.com/questions/3307330/using-joda-date-time-api-to-parse-multiple-formats). – Sotirios Delimanolis Dec 17 '15 at 22:34
1

The date you have shown is in a standard format - the ISO8601 standard.

Joda-Time has a special class for creating DateTimeFormatter objects for this particular standard - the ISODateTimeFormat class.

So you can do this:

DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
LocalDate dob = formatter.parseLocalDate(theDate);

See the documentation for other methods dealing with different variations of the ISO-8601 date format. For the particular string you have shown, the dateTime() method should work.

RealSkeptic
  • 33,993
  • 7
  • 53
  • 79