Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Joda time multiple date format code optimization

Following is the code which converts a string to 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 provides me the desired result but using exception as control flow is not a good design.Please optimize the code.

like image 643
Taha Naqvi Avatar asked Oct 30 '22 22:10

Taha Naqvi


1 Answers

Using Joda , you can try doing this

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

    }

}
like image 166
Ramachandran.A.G Avatar answered Nov 15 '22 06:11

Ramachandran.A.G