SuperCSV Joda时间LocalDate单元处理器接受多种日期格式

时间:2015-06-05 20:10:41

标签: java jodatime datetime-format supercsv

使用SuperCSV我在Joda时间使用ParseLocalDate单元处理器:

private static CellProcessor[] processors = new CellProcessor[] {
    new Optional(new ParseLocalDate(DateTimeFormat.forPattern("MM/dd/yyyy")))
};

这很有效。但是,除了接受MM/dd/yyyy格式之外,我还想接受yyyy-MM-dd,但我一直无法弄清楚如何提供两个不同的单元处理器来处理同一个字段。我试着将它们链接起来,但那并没有起作用。知道如何让它接受这两种格式吗?

1 个答案:

答案 0 :(得分:1)

结束搞清楚,您可以定义自定义单元格处理器并处理任意数量的日期格式:

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