Java SuperCSV Joda time LocalDate单元格处理器接受多个日期格式
使用SuperCSV,我将ParseLocalDate单元处理器用于Joda时间:Java SuperCSV Joda time LocalDate单元格处理器接受多个日期格式,java,jodatime,datetime-format,supercsv,Java,Jodatime,Datetime Format,Supercsv,使用SuperCSV,我将ParseLocalDate单元处理器用于Joda时间: private static CellProcessor[] processors = new CellProcessor[] { new Optional(new ParseLocalDate(DateTimeFormat.forPattern("MM/dd/yyyy"))) }; 这很有效。但是,除了接受MM/dd/yyyyy格式外,我还希望接受yyyy-MM-dd,但我无法确定如何提供两个不同的单
private static CellProcessor[] processors = new CellProcessor[] {
new Optional(new ParseLocalDate(DateTimeFormat.forPattern("MM/dd/yyyy")))
};
这很有效。但是,除了接受
MM/dd/yyyyy
格式外,我还希望接受yyyy-MM-dd
,但我无法确定如何提供两个不同的单元处理器来处理同一字段。我试着用链子锁住他们,但没用。你知道如何让它接受这两种格式吗?最后,你可以定义一个自定义单元格处理器,并处理任意数量的日期格式:
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;
}
}