OpenCSV wrong date format

Chandresh Mishra picture Chandresh Mishra · Jul 3, 2018 · Viewed 8.2k times · Source

I am using CsvToBean class of the openCSV. The bean has the date feild.

@CsvDate(value = "yyyy-MM-dd")
@CsvBindByPosition(position = 8)
private Date startDate;

I am doing the negative testing by passing the value "2018-25-02" but it is getting converted to Thu Jan 02 00:00:00 GMT 2020 without throwing any issue.

Answer

rookie picture rookie · Jan 24, 2019

You could create your own custom converter for java 8 LocalDate, e.g.

public class LocalDateConverter extends AbstractBeanField {
    @Override
    protected Object convert(String s) throws CsvDataTypeMismatchException, CsvConstraintViolationException {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate parse = LocalDate.parse(s, formatter);
        return parse;
    }
}

Then you can just annotate your class like:

@CsvCustomBindByPosition(position = 8, converter = LocalDateConverter.class)
private LocalDate startDate;