Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid format issue parsing string to JodaTime

Tags:

java

jodatime

String dateString = "20110706 1607";
    DateTimeFormatter dateStringFormat = DateTimeFormat.forPattern("YYYYMMDD HHMM");
    DateTime dateTime = dateStringFormat.parseDateTime(dateString);

Resulting stacktrace:

Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "201107206 1607" is malformed at " 1607"
    at org.joda.time.format.DateTimeFormatter.parseMillis(DateTimeFormatter.java:644)
    at org.joda.time.convert.StringConverter.getInstantMillis(StringConverter.java:65)
    at org.joda.time.base.BaseDateTime.<init>(BaseDateTime.java:171)
    at org.joda.time.DateTime.<init>(DateTime.java:168)
......

Any thoughts? If I truncate the string to 20110706 with pattern "YYYYMMDD" it works, but I need the hour and minute values as well. What's odd is that I can convert a Jodatime DateTime to a String using the same pattern "YYYYMMDD HHMM" without issue

Thanks for looking

like image 887
RandomUser Avatar asked Dec 21 '22 10:12

RandomUser


1 Answers

Look at your pattern - you're specifying "MM" twice. That can't possibly be right. That would be trying to parse the same field (month in this case) twice from two different bits of the text. Which would you expect to win? You want:

DateTimeFormat.forPattern("yyyyMMdd HHmm")

Look at the documentation for DateTimeFormat to see what everything means.

Note that although calling toString with that pattern will produce a string, it won't produce the string you want it to. I wouldn't be surprised if the output even included "YYYY" and "DD" due to the casing, although I can't test it right now. At the very least you'd have the month twice instead of the minutes appearing at the end.

like image 193
Jon Skeet Avatar answered Jan 04 '23 22:01

Jon Skeet