java - 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 不保存数据格式。
提前致谢。
解决方案
如果您使用宽松的 DateTimeFormatter 您的日期工作,即:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseLenient()
.appendPattern("dd/MM/yyyy").appendLiteral(",").appendPattern("HH:mm:ss")
.toFormatter();
推荐阅读
- csv - 使用 awk 获取正确的列并定义要使用的分隔符和分隔符?
- cognos - Cognos Analytics - 合并两个维度时不加载报表
- node.js - 节点 process.argv 正在剥离插入符号 (^)
- java - 蒙特卡罗模拟 - 如果两个整数互质的概率?
- python - IndexError: string index out of range - 当索引没有超出被调用列表的范围时,我如何得到这个错误?
- python - 如何从 Temp-Mail Selenium 中获取电子邮件值
- c# - C# Seleium 有没有一种方法可以找到不同格式的 href 的 LinkText?
- python - 你如何使用 Toplevel() 在 Tkinter 中分离/打开一个新的图形窗口?
- mapping - 从 HERE Studio 生成室内地图
- go - 解码 Protobuf 文本