Menu

#56 Joda DateTime cell processor

Outstanding
closed
nobody
None
1
2015-02-14
2014-11-08
No

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

}

Discussion

  • James Bassett

    James Bassett - 2015-01-24
    • status: open --> closed
     
  • James Bassett

    James Bassett - 2015-01-24
     

Log in to post a comment.