Question

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) 
Was it helpful?

Solution

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

OTHER TIPS

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top