如何从 Csv 文件解析 OffsetDateTime

How To Parse OffsetDateTime From Csv File

我正在尝试使用 opencsv 来解析这样的 csv 文件:

2020-09-18 06:50:00.000000

我正尝试按照本教程添加已解析的数据:https://attacomsian.com/blog/spring-boot-upload-parse-csv-file。这是我的模型:

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

我尝试解析 offsetDateTime

通过做:

OffsetDateTime odt = OffsetDateTime.parse (myIndPrds.get (i) .getTime ());

录制之前

但你好像不想做

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

感谢您的帮助

CSV 中的日期时间字符串(例如,您在问题中提到的 2020-09-18 06:50:00.000000)没有时区偏移量,因此最合适的解析类型是 LocalDateTime.

您可以定义转换器 class 将日期时间字符串从 CSV 转换为 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;
    }
}

然后您可以将该字段注释为

@CsvBindByName(converter = LocalDateTimeConverter.class)
private LocalDateTime time;

但是,如果您仍想将日期时间字符串解析为 OffsetDateTime,请按以下步骤操作:

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
    }
}

然后您可以将该字段注释为

@CsvBindByName(converter = OffsetDateTimeConverter.class)
private OffsetDateTime time;

此解析工作原理的快速演示:

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

您不需要定义转换器class。您可以简单地按照

@CsvDate(value = "uuuu-MM-dd HH:mm:ss.n")
@CsvBindByName
private LocalDateTime time;