Java 日期时间格式化程序

标签 java datetime

我正在尝试读取需要解析特定日期值的 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/

相关文章:

PHP 强制日期为 CSV 中的文本

java - 将字符串转换为 GregorianCalendar

python - 将日期时间从 Objective C 传递到 Django

datetime - "UTC"是 RFC 1123 规范的有效时区名称吗?

python - DataFrame 中的日期为工作日

r - POSIXlt 组件的提取在 R 3.4.4 中运行良好,但在 R 3.5.0 中出现错误。为什么?

java - 从 MvcResult 对象获取响应

java - 从 Android 触发 Prolific Barcode Scanner 设备

java - 第二次加载后位图大小超出虚拟机预算

java - 从 AES 加密字符串中删除\r 和\n