java - 将字符串 ("2022-12-23T07:20:00") 时间转换为 ZonedDateTime

标签 java string java-time zoneddatetime

我试图将字符串时间转换为 ZonedDateTime 但没有找到解决方案。这是时间“2022-12-23T07:20:00”的字符串格式

我尝试过这种方法

字符串 stringDate = "2022-12-23T07:20:00";

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
ZonedDateTime ztdOfDateOfPurchase = ZonedDateTime.parse(stringDate , dateTimeFormatter);

 this error is coming=> java.time.format.DateTimeParseException: Text '2022-12-23T07:20:00' could not be parsed at index 19

最佳答案

使用LocalDateTime#parse简单地解析您的日期时间字符串并添加适用的 ZoneId 以获取 ZonedDateTime

请注意,java.time API 基于 ISO 8601因此,您不需要 DateTimeFormatter 来解析已经采用 ISO 8601 格式的日期时间字符串(例如您的日期时间字符串,2022-12-23T07:20:00)。

演示:

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

class Main {
    public static void main(String[] args) {
        LocalDateTime ldt = LocalDateTime.parse("2022-12-23T07:20:00");

        // Replace ZoneId.systemDefault() with the applicable zone ID e.g.
        // ZoneId.of("America/New_York")
        ZonedDateTime zdt = ZonedDateTime.of(ldt, ZoneId.systemDefault());
        System.out.println(zdt);

        // Alternatively,
        zdt = ldt.atZone(ZoneId.systemDefault());
        System.out.println(zdt);
    }
}

我所在时区的输出:

2022-12-23T07:20Z[Europe/London]
2022-12-23T07:20Z[Europe/London]

Trail: Date Time 了解有关现代日期时间 API 的更多信息

关于java - 将字符串 ("2022-12-23T07:20:00") 时间转换为 ZonedDateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74916917/

相关文章:

c# - String.Substring解释

java - java.time API 如何确定政府对区域规则的更改?

java - 检查给定格式字符串可用于解析的 Temporal 类型

java - 将 Java 日期转换为 OffsetDateTime

java - 使用 eclipse 在 java 中使用 windows 应用程序

java - TDD 中的模拟值

java - 如何为java jtable创建鼠标双监听器

java - (Java 7 NIO.2) 监视服务线程的自定义名称

C缓冲区溢出

java - 使用文件中的字符串的建议