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) {
This code gives me the desired result, but using an exception, since the control flow is not a good design. Please optimize the code.
source share