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) 
  • 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. – Ankit Bansal Mar 26 '13 at 16:48

2 Answers2

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
Magnilex
  • 11,584
  • 9
  • 62
  • 84
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).

Clockwork-Muse
  • 12,806
  • 6
  • 31
  • 45