【问题标题】:How To Parse OffsetDateTime From Csv File如何从 Csv 文件中解析 OffsetDateTime
【发布时间】:2020-12-01 09:31:36
【问题描述】:

我正在尝试使用 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";
    }

感谢您的帮助

【问题讨论】:

    标签: java spring-boot opencsv offsetdatetime


    【解决方案1】:

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

    您可以定义一个转换器类来将日期时间字符串从 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

    您不需要定义转换器类。你可以简单地这样做

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-29
      • 1970-01-01
      • 2011-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-08
      • 1970-01-01
      相关资源
      最近更新 更多