I am trying to use opencsv to parse a csv file like this:
2020-09-18 06:50:00.000000
I am trying to add the parsed data following this tutorial: https://attacomsian.com/blog/spring-boot-upload-parse-csv-file. This is my model:
public class MyIndPrd implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@CsvBindByName
private String service;
@CsvBindByName
private OffsetDateTime time;
@CsvBindByName
private Long nbAppels;
@CsvBindByName
private Double tempsDeReponseMoyenMillisecondes;
@CsvBindByName
private Long volume;
@CsvBindByName
private Double tempsDeReponseMoyenSecondes;
}
I try to parse the offsetDateTime
by doing :
OffsetDateTime odt = OffsetDateTime.parse (myIndPrds.get (i) .getTime ());
before recording it
but it doesn't seem like you want to do it
@PostMapping("/upload-csv-file")
public String uplaodCSVFile(@RequestParam("file") MultipartFile file, Model model){
if (file.isEmpty()){
model.addAttribute("message", "Veuillez selectionner un fichier csv à importer.");
model.addAttribute("status", false);
}else try (Reader reader = new BufferedReader(new InputStreamReader(file.getInputStream()))) {
// create csv bean reader
CsvToBean<MyIndPrd> csvToBean = new CsvToBeanBuilder(reader)
.withType(MyIndPrd.class)
.withSeparator(';')
.withIgnoreLeadingWhiteSpace(true)
.build();
// convert CsvToBean object
List<MyIndPrd> myIndPrds = csvToBean.parse();
for (int i = 0;i<myIndPrds.size();i++){
OffsetDateTime odt = OffsetDateTime.parse(myIndPrds.get(i).getTime());
MyIndPrd ind = new MyIndPrd();
ind.setService(myIndPrds.get(i).getService());
ind.setTime(odt);
ind.setNbAppels(Long.valueOf(myIndPrds.get(i).getNbAppels()));
ind.setVolume(Long.valueOf(myIndPrds.get(i).getVolume()));
ind.setTempsDeReponseMoyenMillisecondes(Double.valueOf(myIndPrds.get(i).getTempsDeReponseMoyenMillisecondes()));
ind.setTempsDeReponseMoyenSecondes(Double.valueOf(myIndPrds.get(i).getTempsDeReponseMoyenSecondes()));
iMyIndPrdService.saveMyData(ind);
}
model.addAttribute("myIndProdCsv", myIndPrds);
model.addAttribute("status", true);
} catch (Exception ex) {
model.addAttribute("message", "An error occurred while processing the CSV file.");
model.addAttribute("status", false);
}
return "mon-dasboard";
}
Thanks for your help
Your date-time string (e.g. 2020-09-18 06:50:00.000000
as you have mentioned in the question) in the CSV does not have timezone-offset and therefore the most appropriate type to parse it into would be LocalDateTime
.
You can define a converter class to convert the date-time string from the CSV into LocalDateTime
.
public class LocalDateTimeConverter extends AbstractBeanField {
@Override
protected Object convert(String s) throws CsvDataTypeMismatchException, CsvConstraintViolationException {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.n");
LocalDateTime ldt = LocalDateTime.parse(strDate, dtf);
return ldt;
}
}
and then you can annotate the field as
@CsvBindByName(converter = LocalDateTimeConverter.class)
private LocalDateTime time;
However, if you still want to parse your date-time string into OffsetDateTime
, here is how you can do it:
public class OffsetDateTimeConverter extends AbstractBeanField {
@Override
protected Object convert(String s) throws CsvDataTypeMismatchException, CsvConstraintViolationException {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.n").withZone(ZoneId.systemDefault());
ZonedDateTime zdt = ZonedDateTime.parse(strDate, dtf);
OffsetDateTime odt = zdt.toOffsetDateTime();
return odt
}
}
and then you can annotate the field as
@CsvBindByName(converter = OffsetDateTimeConverter.class)
private OffsetDateTime time;
A quick demo of how this parsing works:
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
String strDate = "2020-09-18 06:50:00.000000";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.n").withZone(ZoneId.systemDefault());
ZonedDateTime zdt = ZonedDateTime.parse(strDate, dtf);
OffsetDateTime odt = zdt.toOffsetDateTime();
System.out.println(zdt);
System.out.println(odt);
}
}
OpenCSV 5
You do not need to define a converter class. You can simply do it as
@CsvDate(value = "uuuu-MM-dd HH:mm:ss.n")
@CsvBindByName
private LocalDateTime time;