JodaTime goodies – flexible parsing

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") ;
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s