Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCSV wrong date format

Tags:

java

date

opencsv

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.

like image 547
Chandresh Mishra Avatar asked Jul 03 '18 12:07

Chandresh Mishra


2 Answers

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;
like image 110
rookie Avatar answered Sep 19 '22 13:09

rookie


OpenCSV 5

OpenCSV 5.x onwards supports Java 8 java.time APIs natively.

To quote the documentation:

Full support for the Java 8 Time API is included. Conversion to and from all JDK-types that implement TemporalAccessor is included.

The following should therefore suffice:

@CsvDate(value = "yyyy-MM-dd")
@CsvBindByPosition(position = 8)
private LocalDate startDate;
like image 20
sxc731 Avatar answered Sep 20 '22 13:09

sxc731