Using SuperCSV I am utilizing the ParseLocalDate cell processor for Joda time:
private static CellProcessor[] processors = new CellProcessor[] {
new Optional(new ParseLocalDate(DateTimeFormat.forPattern("MM/dd/yyyy")))
};
This works great. However, in addition to accepting a MM/dd/yyyy
format, I would also like to accept yyyy-MM-dd
, but I have been unable to figure out how to provide two distinct cell processors to handle the same field. I tried chaining them but that didn't work. Any idea how I can get it to accept both formats?
Ended up figuring it out, you can define a custom cell processor and process as many date formats as you like:
public class ParseLocalDate extends CellProcessorAdaptor {
public ParseLocalDate() {
super();
}
public ParseLocalDate(CellProcessor next) {
super(next);
}
@Override
public Object execute(Object value, CsvContext context) {
validateInputNotNull(value, context);
DateTimeFormatter[] dateFormats = {
DateTimeFormat.forPattern("yyyy-MM-dd"),
DateTimeFormat.forPattern("MM/dd/yyyy") };
LocalDate date = null;
for (DateTimeFormatter dtf : dateFormats) {
try {
date = LocalDate.parse(value.toString(), dtf);
break;
} catch (Exception e) {
// was not able to be parsed with this format, do nothing
}
}
if (date == null)
throw new SuperCsvCellProcessorException("Date could not be parsed", context, this);
return date;
}
}