Joda DateTime cell processor
A fast, programmer-friendly, free CSV library for Java
Brought to you by:
jamesbassett,
kbg
I created a Joda DateTime cell processor.
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.supercsv.cellprocessor.CellProcessorAdaptor;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.exception.SuperCsvCellProcessorException;
import org.supercsv.util.CsvContext;
public class JodaDateTimeSuperCsvCellProcessor extends CellProcessorAdaptor {
private final String dateFormat;
public JodaDateTimeSuperCsvCellProcessor(final String dateFormat) {
super();
checkPreconditions(dateFormat);
this.dateFormat = dateFormat;
}
public JodaDateTimeSuperCsvCellProcessor(final String dateFormat, CellProcessor next) {
super(next);
checkPreconditions(dateFormat);
this.dateFormat = dateFormat;
}
public Object execute(Object value, CsvContext context) {
validateInputNotNull(value, context);
if (!(value instanceof String)) {
throw new SuperCsvCellProcessorException(String.class, value, context, this);
}
try {
final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormat.forPattern(dateFormat);
final DateTime dateTime = DATE_TIME_FORMATTER.parseDateTime((String) value);
return next.execute(dateTime, context);
} catch (IllegalArgumentException e) {
throw new SuperCsvCellProcessorException(String.format("Could not parse '%s' as a day", value), context, this);
}
}
private static void checkPreconditions(final String dateFormat) {
if (dateFormat == null) {
throw new NullPointerException("dateFormat should not be null");
}
}
}
Migrated to GitHub issues: https://github.com/super-csv/super-csv/issues/15