我正在尝试读取需要解析特定日期值的 CSV 文件。 但是我得到一个我无法放置的 DateTimeParseException。
我要读取的字段是一个日期字段,如下所示:
2016 年 5 月 8 日
我使用的代码:
LocalDate date = LocalDate.parse(row[3], DateTimeFormatter.ofPattern("d-M-yy"));
其中 row[3]
是我从CSV 文件。
我得到的异常:无法在索引 3 处解析文本“08-May-16”
我认为 d-M-yy
应该能够读取一年中的月份的一位数、两位数和字母表示是否错误?
编辑:我已经尝试过月份 MMM-MM-M 以及日期字段的 dd-d 。我仍然得到同样的异常(exception)。
最佳答案
这里的问题是您在创建 DateTimeFormatter
时没有提供 Locale
- 您需要使用支持的 Locale
该格式:
System.out.println(LocalDate.parse("08-May-2016", DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.ENGLISH)));
输出:
2016-05-08
这行不通:
System.out.println(LocalDate.parse("08-May-2016", DateTimeFormatter.ofPattern("dd-LLL-yyyy", Locale.ENGLISH)));
输出:
Exception in thread "main" java.time.format.DateTimeParseException: Text '08-May-2016' could not be parsed at index 3
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalDate.parse(LocalDate.java:400)
关于Java 日期时间格式化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37137168/