异常使用LocalDateTime解析DateTime时无法从TemporalAccessor获取LocalDateTime

时间:2017-06-01 06:22:36

标签: java datetime java-8

解析DateTime时获取异常。这是我在这里失踪的东西

DateTimeFormatter formatter =  DateTimeFormatter.ofPattern("0DDDHHmmss");
DateTimeFormatter.ofPattern("0DDDHHmmss");
LocalDateTime date = LocalDateTime.parse("0365231109", formatter).withYear(2016);

以下是我得到的例外

Exception in thread "main" java.time.format.DateTimeParseException: Text '0365231109' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {DayOfYear=365},ISO resolved to 23:11:09 of type java.time.format.Parsed
    at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
    at java.time.LocalDateTime.parse(LocalDateTime.java:492)
    at AutocomFDParser.main(AutocomFDParser.java:204)
Caused by: java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {DayOfYear=365},ISO resolved to 23:11:09 of type java.time.format.Parsed
    at java.time.LocalDateTime.from(LocalDateTime.java:461)
    at java.time.format.Parsed.query(Parsed.java:226)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    ... 2 more
Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {DayOfYear=365},ISO resolved to 23:11:09 of type java.time.format.Parsed
    at java.time.LocalDate.from(LocalDate.java:368)
    at java.time.LocalDateTime.from(LocalDateTime.java:456)

2 个答案:

答案 0 :(得分:4)

您没有在输入字符串中指定要转换为LocalDateTime的年份。

LocalDateTime必须与一年相关联。

因此抛出以下异常:

  

无法从TemporalAccessor获取LocalDate:{DayOfYear = 365},ISO   解析为java.time.format.Parsed类型的23:11:09

您可以使用以下内容设置假日期作为输入:withYear(2016)

String stringInput = "02000365231109";
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("0yyyyDDDHHmmss");
LocalDateTime date2 = LocalDateTime.parse(stringInput, formatter2).withYear(2016);

如果无法直接修改输入,则可以在调用parse()方法之前创建具有正确格式的新String:

String stringInput = "0365231109";
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("0yyyyDDDHHmmss");
stringInput = "02000" + stringInput.substring(1);
LocalDateTime date2 = LocalDateTime.parse(stringInput, formatter2).withYear(2016);

答案 1 :(得分:1)

第一次您的日期时间模式更像是Duration而不是LocalDateTime。您可以使用TemporalAccessor#queryDuration创建TemporalAccessor。例如:

List<TemporalField> fields = Arrays.asList(DAY_OF_YEAR, HOUR_OF_DAY
        , MINUTE_OF_HOUR, SECOND_OF_MINUTE);

Duration duration = DateTimeFormatter.ofPattern("0DDDHHmmss").parse("0366231109")
    .query(temporal -> fields.stream().reduce(
            Duration.ZERO,
            (it, field) -> it.plus(field.getFrom(temporal), field.getBaseUnit()),
            Duration::plus
    ));

那么您可以在LocalDateTime实例上创建Duration基础。例如:

LocalDateTime start=LocalDateTime.of(Year.of(2016).atDay(1),LocalTime.of(0, 0, 0));
LocalDateTime result = start.plus(duration);

System.out.println(result);

输出

  

&#34; 2017-01-01T23:11:09&#34;