无法从TemporalAccessor获取LocalTime [英] Unable to obtain LocalTime from TemporalAccessor

查看:330
本文介绍了无法从TemporalAccessor获取LocalTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java 8时代还很陌生,所以这个问题可能有一个明显的答案,但是在阅读了其他类似的SO问题之后,我无法发现导致我问题的任何相似之处.

I am pretty new to Java 8 time, so this question probably has an obvious answer but after reading the other similar SO questions I couldn't spot any similarities which cause my issue.

这是我的课程:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class LocalDateTimeIssue {

    public static void main(String[] args) {
        String dateTimeString = "18-04-2019 12:14:46";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm:ss", Locale.US);
        LocalDateTime ldt = LocalDateTime.parse(dateTimeString , dtf);
        System.out.println(ldt.getSecond());
    }

}

这将引发以下异常:

Exception in thread "main" java.time.format.DateTimeParseException: Text '18-04-2019 12:14:46' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {MilliOfSecond=0, MinuteOfHour=14, HourOfAmPm=0, NanoOfSecond=0, MicroOfSecond=0, SecondOfMinute=46},ISO resolved to 2019-04-18 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 LocalDateTimeIssue.main(LocalDateTimeIssue.java:10)
Caused by: java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {MilliOfSecond=0, MinuteOfHour=14, HourOfAmPm=0, NanoOfSecond=0, MicroOfSecond=0, SecondOfMinute=46},ISO resolved to 2019-04-18 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 LocalTime from TemporalAccessor: {MilliOfSecond=0, MinuteOfHour=14, HourOfAmPm=0, NanoOfSecond=0, MicroOfSecond=0, SecondOfMinute=46},ISO resolved to 2019-04-18 of type java.time.format.Parsed
    at java.time.LocalTime.from(LocalTime.java:409)
    at java.time.LocalDateTime.from(LocalDateTime.java:457)
    ... 4 more

推荐答案

必须为dd-MM-yyyy HH:mm:ss

 h       clock-hour-of-am-pm (1-12)  number            12
 H       hour-of-day (0-23)          number            0

因为在您的示例中,12个可以是AM或PM.

Because in your example, the 12 can either be AM or PM.

由于信息丢失,格式化程序无法在AM或PM之间做出决定:

The formatter cannot decide between AM or PM as the information is missing:

 a       am-pm-of-day                text              PM

两者都是可能的,因此会出现错误Unable to obtain LocalTime.

Both are possible, thus the error Unable to obtain LocalTime occurs.

这篇关于无法从TemporalAccessor获取LocalTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆