简体   繁体   English

解析数据时抛出异常

[英]Exception thrown when parsing data

Sorry if this is a rookie question, but I have the following problem: every time I try to parse a string into a LocalDate type, with a specific format (ddMMyyy) I get the following message:抱歉,如果这是一个菜鸟问题,但我有以下问题:每次我尝试将字符串解析为具有特定格式 (ddMMyyy) 的LocalDate类型时,我都会收到以下消息:

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

At first I thought that maybe I did something wrong in a different part of the code and I tried to isolate just the part where I'm doing the parsing to test it, but no luck.起初我想也许我在代码的不同部分做错了什么,我试图隔离我正在解析的部分来测试它,但没有运气。 This is the test code:这是测试代码:

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

Later Edit: I tried different formats: "dd/MM/yyyy", "dd-MM-yyyy", "ddMMyyyy", they still didn't work.后来编辑:我尝试了不同的格式:“dd/MM/yyyy”、“dd-MM-yyyy”、“ddMMyyyy”,它们仍然不起作用。

Clearly, your pattern does not match your string.显然,您的模式与您的字符串不匹配。

Your string contains no spaces while your pattern does.您的字符串不包含空格,而您的模式包含空格。

Your string contains a two digit month while your pattern is expecting a three letter abbreviation of the month name.您的字符串包含两位数的月份,而您的模式需要月份名称的三个字母缩写。

Try the following code:试试下面的代码:

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

All the valid patterns are detailed and explained in the javadoc of class DateTimeFormatter class DateTimeFormatterjavadoc中详细说明了所有有效模式

import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class FormatDate {

public static void main(String... args) throws ParseException {
    String in = "06071994";
    DateTimeFormatter format = DateTimeFormatter.ofPattern("ddMMyyyy");
    LocalDate BirthDay = LocalDate.parse(in, format);
    System.out.println(BirthDay);
  }
}

Edit 1 : Problem with the code was that the input was in the format ddMMyyyy(06071994) and the format was dd MM yyyy (should have been ddMMyyyy).编辑1 :代码的问题是输入格式为ddMMyyyy(06071994),格式为dd MM yyyy (应该是ddMMyyyy)。 So now parser sees that input and format to parse are not same hence it throws error.所以现在解析器看到要解析的输入和格式不一样,因此它会抛出错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM