我试图将字符串时间转换为 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/