如何从csv文件解析offsetdatetime

mhd8tkvw  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(540)

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

谢谢你的帮助

wnavrhmk

wnavrhmk1#

日期时间字符串(例如。 2020-09-18 06:50:00.000000 正如您在问题中提到的)csv中没有时区偏移,因此最适合将其解析为 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;

相关问题