11

Shouldn't a String formatted with a specific DateTimeFormatter be able to be parsed using LocalDateTime.parse()?

Test

DateTimeFormatter formatter = ISODateTimeFormat.dateTimeNoMillis()
LocalDateTime ldt = new LocalDateTime()
String val = ldt.toString(formatter)
System.out.println(val) //2013-03-26T13:10:46
// parse() throws java.lang.IllegalArgumentException: Invalid format: "2013-03-26T13:10:46" is too short
LocalDateTime nldt = LocalDateTime.parse(val, formatter) 
1
  • 3
    I would say this is a bug with JodaTime. It should parse any string with format as well as formatter is object of DateTimeFormatter which is not happening. Commented Mar 26, 2013 at 16:48

2 Answers 2

9

Have a look at the JavaDoc:

Returns a basic formatter that combines a basic date and time without millis, separated by a 'T' (yyyyMMdd'T'HHmmssZ). The time zone offset is 'Z' for zero, and of the form '±HHmm' for non-zero. The parser is strict by default, thus time string 24:00 cannot be parsed.

The key here seems to be The time zone offset is 'Z' for zero, and of the form '±HHmm' for non-zero. Joda Time obviously expects time zone information for parse().

I appended "Z" to your parsed date String and it works better:

DateTimeFormatter formatter = ISODateTimeFormat.dateTimeNoMillis();
LocalDateTime ldt = new LocalDateTime();
String val = ldt.toString(formatter);
System.out.println(val);    
val += "Z";
LocalDateTime nldt = LocalDateTime.parse(val, formatter);
System.out.println(nldt.toString());

Output is:

2013-03-26T17:50:06
2013-03-26T17:50:06.000
Sign up to request clarification or add additional context in comments.

Comments

2

The formatter also throws the error if formatter.parseLocalDateTime(val) is called, which is what LocalDateTime.parse(...) is calling directly (ie, the naive call).

So, then, it's a factor of the format that is expected - which in this case is yyyy-MM-dd'T'HH:mm:ssZZ; basically, it's complaining that you haven't passed a timezone.

I don't know if this actually qualifies as a 'bug'; in the short term, obviously a custom format may be used, or look at ISODateTimeFormat.localDateOptionalTimeParser(), which appears to be what you want (it's the default parser used by LocalDateTime).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.