Parsing dates in Java with JodaTime is easy.
1. instantiate a date time formatter
DateTimeFormatter dateTimeFormatter =
DateTimeFormat.forPattern("yyyyMMddHH:mm:ss.SSS") ;
2. …and parse the date time
dateTimeFormatter.parseDateTime("20120515 09:30:25.123") ;
3. but when the date time format changes (say to include a timezone)…alarm bells.
dateTimeFormatter.parseDateTime("20120515 09:30:25.123 +0000") ;
//results in//
java.lang.IllegalArgumentException:
Invalid format: "20120515 09:30:25.123 +0000" is malformed at " +0000"
4. Fortunately the JodaTime api includes a DateTimeFormatterBuilder which can be used to build a dateTimeFormatter customised with multiple printers and parsers.
DateTimeFormatter dateTimeFormatter=
DateTimeFormat.forPattern("yyyyMMddHH:mm:ss.SSS") ;
DateTimeFormatter dateTimeFormatterWithTimeZone=
DateTimeFormat.forPattern("yyyyMMdd HH:mm:ss.SSS Z");
DateTimeFormatter optionalTimeZoneFormatter=
new DateTimeFormatterBuilder()
.append(null, //because no printing is required
new DateTimeParser[]{dateTimeFormatter.getParser(),
dateTimeFormatterWithTimeZone.getParser()}).toFormatter();
5. now the same DateTimeFormatter handles different date time formats
optionalTimeZoneFormatter.parseDateTime("20120515 09:30:25.123") ;
optionalTimeZoneFormatter.parseDateTime("20120515 09:30:25.123 +0000") ;



























