gpt4 book ai didi

java - 没有分隔符的本地日期解析不起作用

转载 作者:搜寻专家 更新时间:2023-11-01 01:48:55 25 4
gpt4 key购买 nike

我的日期格式如下:

The year in four digits then the week number in two digits.

例如,2018 年的第四周将是201804

我在使用 Java 8 的 LocalDateDateTimeFormatterBuilder 解析这些日期时遇到问题。

这是我尝试解析日期的方式:

LocalDate.parse(
"201804",
new DateTimeFormatterBuilder().appendPattern("YYYYww").parseDefaulting(WeekFields.ISO.dayOfWeek(), 1).toFormatter()
);

执行抛出以下异常:

java.time.format.DateTimeParseException: Text '201804' could not be parsed at index 0

奇怪的是,当我在日期部分之间添加分隔符时,不再抛出异常:

LocalDate.parse(
"2018 04",
new DateTimeFormatterBuilder().appendPattern("YYYY ww").parseDefaulting(WeekFields.ISO.dayOfWeek(), 1).toFormatter()
);

结果:

2018-01-22

格式化程序是否遗漏了什么?

最佳答案

您可以使用 appendValue

This method supports a special technique of parsing known as 'adjacent value parsing'. This technique solves the problem where a value, variable or fixed width, is followed by one or more fixed length values. The standard parser is greedy, and thus it would normally steal the digits that are needed by the fixed width value parsers that follow the variable width one.

No action is required to initiate 'adjacent value parsing'. When a call to appendValue is made, the builder enters adjacent value parsing setup mode.

所以这是可行的:

LocalDate.parse(
"201804",
new DateTimeFormatterBuilder()
.appendValue(YEAR, 4)
.appendValue(ALIGNED_WEEK_OF_YEAR, 2)
.parseDefaulting(WeekFields.ISO.dayOfWeek(), 1).toFormatter()
);

关于java - 没有分隔符的本地日期解析不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54513734/

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