java - 解析数据时抛出异常
问题描述
抱歉,如果这是一个菜鸟问题,但我有以下问题:每次我尝试将字符串解析为LocalDate
具有特定格式(ddMMyyy)的类型时,我都会收到以下消息:
Exception in thread "main" java.time.format.DateTimeParseException: Text '06071994' could not be parsed at index 2
at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2046)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
at java.base/java.time.LocalDate.parse(LocalDate.java:428)
at jujj.main(jujj.java:7)
Process finished with exit code 1
起初我想也许我在代码的不同部分做错了什么,我试图隔离我正在解析的部分来测试它,但没有运气。这是测试代码:
String in = "06071994";
DateTimeFormatter format = DateTimeFormatter.ofPattern ( "dd MM yyyy" );
LocalDate BirthDay = LocalDate.parse ( in, format );
System.out.println ( in );
后来编辑:我尝试了不同的格式:“dd/MM/yyyy”、“dd-MM-yyyy”、“ddMMyyyy”,它们仍然不起作用。
解决方案
显然,您的模式与您的字符串不匹配。
您的字符串不包含空格,而您的模式包含空格。
您的字符串包含两位数的月份,而您的模式需要月份名称的三个字母缩写。
试试下面的代码:
String in = "06071994";
DateTimeFormatter format = DateTimeFormatter.ofPattern ( "ddMMyyyy" );
LocalDate BirthDay = LocalDate.parse ( in, format );
System.out.println ( BirthDay );
所有有效模式在类的javadoc中都有详细说明DateTimeFormatter
推荐阅读
- bazel - 使用 git_repository-bazel 导入私有存储库
- winapi - “推送偏移变量”在 MASM64 上产生“错误 A2070:无效指令操作数”
- python - 使用 $ 金额作为损失来衡量分类性能
- python - 熊猫阅读带有大文本 fpr nlp 的 csv
- angular - 当 Moment 语言环境更改时,Angular Material DatePicker 不会更改
- sql-server - 为什么此查询中的变量不能返回任何值?
- python - 如何在python列表中使用索引?
- angular - 将 JS 日期时间格式化为更正 ISO 格式
- parsing - X 后响应退出
- spring - 如何使用 JUnit 运行 Spring AOP?