我下面有一个将字符串转换为Instant对象的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

如何解决错误?

推荐答案

我发布这篇文章是为了展示上述 comments 的实质,这些 comments 几乎完全正确:

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));
    }
}

Java相关问答推荐

我正在try 对用户输入的整元进行气泡排序(Java)

无法在Java中使用Curve secp 256 k1验证JWT

javafx getHostServices(). showDocument()调出Chrome而不是默认浏览器(Linux)

为什么接口中的主函数而不是类中的主函数在Java 17中编译和运行没有问题?

@ IdClass with @ Inheritance(策略= InheritanceType. SINGLE_TABLE)

将数组整体转换为链接表

FALSE:它应该在什么时候使用?

我无法获取我的Java Spring应用程序的Logback跟踪日志(log)输出

Mac上的全屏截图在使用JavaFX时不能正常工作吗?

使用多个RemoteDatabase对象的一个线程

WebSockets和Spring Boot安全性出现错误401

为什么Collectors.toList()不能保证易变性

在处理2个映射表时,没有更多的数据可从套接字读取

Java嵌套流查找任意值

如何利用OpenTelemeter将初始值(零)输出到普罗米修斯

为什么Spring要更改Java版本配置以及如何正确设置?

spring 更新多项管理关系

在数组中查找素数时出现逻辑错误

spring 数据Elastic search 与 spring 启动数据Elastic search 之间的区别是什么?

Cucumber中第二个网页的类对象未初始化