gpt4 book ai didi

java - 使用 LocalDateTime 解析 DateTime 时异常无法从 TemporalAccessor 获取 LocalDateTime

转载 作者:行者123 更新时间:2023-12-01 01:13:20 28 4
gpt4 key购买 nike

解析 DateTime 时出现异常。我在这里缺少什么

DateTimeFormatter formatter =  DateTimeFormatter.ofPattern("0DDDHHmmss");
DateTimeFormatter.ofPattern("0DDDHHmmss");
LocalDateTime date = LocalDateTime.parse("0365231109", formatter).withYear(2016);

以下是我遇到的异常

Exception in thread "main" java.time.format.DateTimeParseException: Text '0365231109' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {DayOfYear=365},ISO resolved to 23:11:09 of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
at AutocomFDParser.main(AutocomFDParser.java:204)
Caused by: java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {DayOfYear=365},ISO resolved to 23:11:09 of type java.time.format.Parsed
at java.time.LocalDateTime.from(LocalDateTime.java:461)
at java.time.format.Parsed.query(Parsed.java:226)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
... 2 more
Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {DayOfYear=365},ISO resolved to 23:11:09 of type java.time.format.Parsed
at java.time.LocalDate.from(LocalDate.java:368)
at java.time.LocalDateTime.from(LocalDateTime.java:456)

最佳答案

您没有在要转换为 LocalDateTime 的输入字符串中指定年份。

LocalDateTime 必须与年份相关联。

因此抛出以下异常:

Unable to obtain LocalDate from TemporalAccessor: {DayOfYear=365},ISO resolved to 23:11:09 of type java.time.format.Parsed

你可以设置一个假的日期作为你覆盖它的输入: withYear(2016) :

String stringInput = "02000365231109";
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("0yyyyDDDHHmmss");
LocalDateTime date2 = LocalDateTime.parse(stringInput, formatter2).withYear(2016);

如果您不能直接修改输入,您可以在调用 parse() 方法之前创建一个具有正确格式的新字符串:

String stringInput = "0365231109";
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("0yyyyDDDHHmmss");
stringInput = "02000" + stringInput.substring(1);
LocalDateTime date2 = LocalDateTime.parse(stringInput, formatter2).withYear(2016);

关于java - 使用 LocalDateTime 解析 DateTime 时异常无法从 TemporalAccessor 获取 LocalDateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44299927/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com