Java Joda multiple date format code optimization

Below is the code that converts the string to a Joda datetime object based on the format string.

public Datetime ConvertDateTime(String dateStr) { List<DateTimeFormatter> FORMATTERS = Arrays.asList( DateTimeFormat.forPattern("MM/dd/yyyy hh:mm:ss.SSS a"), DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS"), DateTimeFormat.forPattern("MM-dd-yyyy hh:mm:ss.SSS a"), DateTimeFormat.forPattern("MM dd yyyy hh:mm:ss.SSS a"), DateTimeFormat.forPattern("MM-dd-yyyy hh.mm.ss.SSS a")); if (dateStr != null) { for (DateTimeFormatter formatter : FORMATTERS) { try { DateTime dt = formatter.parseDateTime(dateStr); return dt; } catch (IllegalArgumentException e) { // Go on to the next format } } } return null; } 

This code gives me the desired result, but using an exception, since the control flow is not a good design. Please optimize the code.

+5
source share
1 answer

Using Joda, you can try to do it.

 import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.DateTimeFormatterBuilder; import org.joda.time.format.DateTimeParser; public class JODATester { public static void main(String[] args) { DateTimeParser[] parserList = { DateTimeFormat.forPattern("MM/dd/yyyy hh:mm:ss.SSS a").getParser(), DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS").getParser(), DateTimeFormat.forPattern("MM-dd-yyyy hh:mm:ss.SSS a").getParser(), DateTimeFormat.forPattern("MM dd yyyy hh:mm:ss.SSS a").getParser(), DateTimeFormat.forPattern("MM-dd-yyyy hh.mm.ss.SSS a").getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parserList).toFormatter(); DateTime date1 = formatter.parseDateTime("2010-01-01 01:01:01.001"); DateTime date2 = formatter.parseDateTime("08/03/2016 03:01:33.790 PM"); System.out.println(date2); System.out.println(date1); // // DateTime dt = new DateTime(); // DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy hh:mm:ss.SSS a"); // String str = fmt.print(dt); // // System.out.println(str); } } 
+2
source

All Articles