首页 > 解决方案 > 解析数据时抛出异常

问题描述

抱歉,如果这是一个菜鸟问题,但我有以下问题:每次我尝试将字符串解析为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”,它们仍然不起作用。

标签: javaparsinglocaldate

解决方案


显然,您的模式与您的字符串不匹配。

您的字符串不包含空格,而您的模式包含空格。

您的字符串包含两位数的月份,而您的模式需要月份名称的三个字母缩写。

试试下面的代码:

String in = "06071994";
DateTimeFormatter format = DateTimeFormatter.ofPattern ( "ddMMyyyy" );
LocalDate BirthDay = LocalDate.parse ( in, format );
System.out.println ( BirthDay );

所有有效模式在类的javadoc中都有详细说明DateTimeFormatter


推荐阅读