无法从 TemporalAccessor 获取 Instant:{},ISO 解析为 java.time.format.Parsed 类型的 2024-04-25T14:32:42

问题描述 投票:0回答:1

我有下面的java程序,它将字符串转换为即时对象。


import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;

public class JenkinsBuildDateFormatApp {
    public static void main(String[] args) {
        String extractedDate = "Apr 25, 2024, 2:32:42 PM";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM dd, yyyy, h:mm:ss a");
        TemporalAccessor ta = dtf.parse(extractedDate);
        System.out.println(Instant.from(ta));
    }
}

当我运行程序时,出现以下错误 -

Exception in thread "main" java.time.DateTimeException: Unable to obtain Instant from TemporalAccessor: > {},ISO resolved to 2024-04-25T14:32:42 of type java.time.format.Parsed
    at java.base/java.time.Instant.from(Instant.java:381)
    at JenkinsBuildDateFormatApp.main(JenkinsBuildDateFormatApp.java:12)
Caused by: java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: InstantSeconds
    at java.base/java.time.format.Parsed.getLong(Parsed.java:215)
    at java.base/java.time.Instant.from(Instant.java:376)
    ... 1 more
Process finished with exit code 1

如何解决该错误?

java date datetime-conversion java.time.instant
1个回答
0
投票

我发布此内容是为了展示上述评论的本质,这些评论几乎完全正确:

import java.util.Locale;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;

public class JenkinsBuildDateFormatApp {
    public static void main(String[] args) {
        String extractedDate = "Apr 25, 2024, 2:32:42 PM";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM dd, yyyy, h:mm:ss a");
        // Above question comments already show why it's necessary
        // to give the Formatter these two attributes for the rest of the
        // code to work (not that this is how one would necessarily *actually write* it)
        dtf = dtf.withLocale(Locale.US).withZone(ZoneId.systemDefault());
        TemporalAccessor ta = dtf.parse(extractedDate);
        System.out.println(Instant.from(ta));
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.