Java 无秒解析瞬间

Java 无秒解析瞬间,java,time,Java,Time,我有日期字符串“2015-05-08T02:56”。正如你所看到的,它没有秒数 当我尝试用以下方法解析它时: Instant instant = Instant.from( DateTimeFormatter.ofPattern("yyyy-MM-dd'T'hh:mm") .parse("2015-05-08T02:56")); 我有例外 Exception in thread "main" java.time.DateTimeException

我有日期字符串
“2015-05-08T02:56”
。正如你所看到的,它没有秒数

当我尝试用以下方法解析它时:

Instant instant = Instant.from(
        DateTimeFormatter.ofPattern("yyyy-MM-dd'T'hh:mm")
                .parse("2015-05-08T02:56"));
我有例外

Exception in thread "main" java.time.DateTimeException: Unable to obtain Instant from TemporalAccessor: {MinuteOfHour=56, HourOfAmPm=2},ISO resolved to 2015-05-08 of type java.time.format.Parsed
    at java.time.Instant.from(Instant.java:378)
    at sample.Main.main(Main.java:18)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: InstantSeconds
    at java.time.format.Parsed.getLong(Parsed.java:203)
    at java.time.Instant.from(Instant.java:373)
    ... 6 more

如何正确解析此日期并用
0
填充秒数?

我忘了指定时区

Instant instant = Instant.from(
        DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm")
                .withZone(ZoneId.of("UTC"))
                .parse("2015-05-08T22:57"));
很好


更新:我还有一个问题,我用了
hh
而不是
hh
,我忘了指定时区

Instant instant = Instant.from(
        DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm")
                .withZone(ZoneId.of("UTC"))
                .parse("2015-05-08T22:57"));
很好


更新:我还遇到了另一个问题,我使用了
hh
而不是
hh

将模式更改为
“yyyy-MM-dd'hh:MM”
,大写为
hh
。@Andreas,为什么它拒绝了
Instant.from(TemporalAccessor)
@AxelH格式,因为
hh
(01-12)没有
a
(AM/PM)是一个不完整的小时值。输入
02:00
可以是凌晨2点或下午2点。要正确解析一天中的小时数,您需要
HH
,或者
HH
+
a
。将模式更改为
“yyyy-MM-dd'T'HH:MM”
,大写为
HH
。@Andreas,为什么它拒绝
Instant.from(TemporalAccessor)
@AxelH格式,因为
HH
(01-12)没有
a
(AM/PM)是一个不完整的小时值。输入
02:00
可以是凌晨2点或下午2点。要正确解析一天中的小时数,您需要
HH
,或者
HH
+
a
。然后将
HH
更改为大写。您需要时区和大写时间才能使此代码正常工作。@Freeman他正确地回答了自己的问题,这是完全正确的。@Michael,是的。我会在我的回答中记下。你把
hh
改为大写。您需要时区和大写时间才能使此代码正常工作。@Freeman他正确地回答了自己的问题,这是完全正确的。@Michael,是的。我会在答覆中记下。