Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Joda Date & Time API to parse multiple formats

I'm parsing third party log files containing date/time using Joda. The date/time is in one of two different formats, depending on the age of the log files I'm parsing.

Currently I have code like this:

try {     return DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss").parseDateTime(datePart); } catch (IllegalArgumentException e) {     return DateTimeFormat.forPattern("E, MMM dd, yyyy HH:mm").parseDateTime(datePart); } 

This works but contravenes Joshua Bloch's advice from Effective Java 2nd Edition (Item 57: Use exceptions only for exceptional conditions). It also makes it hard to determine if an IllegalArgumentException occurs due to a screwed up date/time in a log file.

Can you suggest a nicer approach that doesn't misuse exceptions?

like image 376
Steve McLeod Avatar asked Jul 22 '10 09:07

Steve McLeod


People also ask

Is Joda DateTime deprecated?

So the short answer to your question is: YES (deprecated).

What is Joda date time?

Joda-Time is the most widely used date and time processing library, before the release of Java 8. Its purpose was to offer an intuitive API for processing date and time and also address the design issues that existed in the Java Date/Time API.

How do I change the date format in Joda-time?

How to change the SimpleDateFormat to jodatime? String s = "2014-01-15T14:23:50.026"; DateTimeFormatter dtf = DateTimeFormat. forPattern("yyyy-MM-dd'T'HH:mm:ss. SSSS"); DateTime instant = dtf.


2 Answers

You can create multiple parsers and add them to the builder by using DateTimeFormatterBuilder.append method:

DateTimeParser[] parsers = {          DateTimeFormat.forPattern( "yyyy-MM-dd HH" ).getParser(),         DateTimeFormat.forPattern( "yyyy-MM-dd" ).getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append( null, parsers ).toFormatter();  DateTime date1 = formatter.parseDateTime( "2010-01-01" ); DateTime date2 = formatter.parseDateTime( "2010-01-01 01" ); 
like image 159
btiernay Avatar answered Oct 18 '22 15:10

btiernay


Joda-Time supports this by allowing multiple parsers to be specified - DateTimeFormatterBuilder#append

Simply create your two formatters using a builder and call toParser() on each. Then use the builder to combine them using append.

like image 30
JodaStephen Avatar answered Oct 18 '22 13:10

JodaStephen