Using Univocity, how can I convert a date string value to a Date type in Java

1.1k Views Asked by At

I'll like to parse column zero in a csv file to a particular datatype, in this example a Date Object.

The method below is what I use currently to parse a csv file but I don't know how to incorporate this requirement.

import java.sql.Date;
public class Data {

    @Parsed(index = 0)
        private Date date;
    }
}

public <T> List<T> convertFileToData(File file, Class<T> clazz) {

    BeanListProcessor<T> rowProcessor = new BeanListProcessor<>(clazz);
    CsvParserSettings settings = new CsvParserSettings();
    settings.setProcessor(rowProcessor);
    settings.setHeaderExtractionEnabled(true);

    CsvParser parser = new CsvParser(settings);
    parser.parseAll(file);

    return rowProcessor.getBeans();
}
1

There are 1 best solutions below

0
On BEST ANSWER

All you need is to define the format(s) of your date and you are set:

@Format(formats = {"dd-MMM-yyyy", "yyyy-MM-dd"})
@Parsed(index = 0)
    private Date date;
}

As an extra suggestion, you can also replace a lot of your code by using the CsvRoutines class. Try this:

List<T> beanList = new CsvRoutines(settings).parseAll(clazz, file);

Hope it helps.