没有秒

时间:2017-01-26 11:30:40

标签: 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: 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填充秒数?

1 个答案:

答案 0 :(得分:4)

我忘了指定时区

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

工作正常。

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