使用 SuperCSV,我使用 ParseLocalDate 单元处理器处理 Joda 时间:
private static CellProcessor[] processors = new CellProcessor[] {
new Optional(new ParseLocalDate(DateTimeFormat.forPattern("MM/dd/yyyy")))
};
这很好用。但是,除了接受 MM/dd/yyyy
格式之外,我还想接受 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;
}
}
关于java - SuperCSV Joda 时间 LocalDate 单元处理器接受多种日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30674992/