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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With