首页 > 解决方案 > CSV 文件解析问题:与 Excel 不同的时间格式(使用 Java)

问题描述

我正在尝试从 csv 文件(excel)中读取和解析时间,但由于 Excel 具有删除前导零的功能,因此存在不同的时间格式。像这样:

1/1/2021,9:05:28
1/1/2021,2:48:32
1/1/2021,15:11:00
2/1/2021,14:37:38

09:05:28这样的时间在 Excel 中变成了 9:05:28,不能与 14:37:38 格式一起解析。

ArrayList<className> list = new ArrayList<>();

List<String> lines = Files.readAllLines(Paths.get("file.csv"));
for (int i = 0; i < lines.size(); i++) {
    String[] elements = lines.get(i).split(",");
    // Read data from file
    LocalDate date = LocalDate.parse(elements[0]);
    LocalTime time = LocalTime.parse(elements[1]);
    list.add(new className(date, time));
}
        

如何检测和读取不同格式的时间?我需要它作为时间,而不是字符串。或者也许有什么方法可以在 Excel 中保持前导零?我没有这样做,因为 Excel 不保存数据格式。

提前致谢。

标签: javaexcelcsv

解决方案


如果您使用宽松的 DateTimeFormatter 您的日期工作,即:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    .parseLenient()
    .appendPattern("dd/MM/yyyy").appendLiteral(",").appendPattern("HH:mm:ss")
    .toFormatter();

推荐阅读