Я пытаюсь разобрать простую строку в формате "YYYYww" (например, 201901) в LocalDate, но ни одна из моих попыток не увенчалась успехом.
Я попытался проанализировать его, просто используя шаблон «YYYYww», а также вручную добавив значения в FormatterBuilder. Поскольку моя входная строка не содержит дня, я также настроил средство форматирования по умолчанию на воскресенье.
Вот код, который у меня не работает, с Java 8 (IBM JRE 8.0.5.25).
public static void main(String[] args) {
formatter1(); // Unable to obtain LocalDate from TemporalAccessor
formatter2(); // Text '201901' could not be parsed at index 0
formatter3(); // Text '201901' could not be parsed at index 6
}
public static void formatter1() {
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendValue(WeekFields.ISO.weekBasedYear(), 4, 4, SignStyle.NEVER)
.appendValue(WeekFields.ISO.weekOfYear(), 2, 2, SignStyle.NEVER)
.parseDefaulting(WeekFields.ISO.dayOfWeek(), DayOfWeek.SUNDAY.getValue())
.toFormatter();
LocalDate.parse("201901", formatter);
}
public static void formatter2() {
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("YYYYww")
.parseDefaulting(WeekFields.ISO.dayOfWeek(), DayOfWeek.SUNDAY.getValue())
.toFormatter();
LocalDate.parse("201901", formatter);
}
public static void formatter3() {
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseLenient()
.appendPattern("YYYYww")
.parseDefaulting(WeekFields.ISO.dayOfWeek(), DayOfWeek.SUNDAY.getValue())
.toFormatter();
LocalDate.parse("201901", formatter);
}
Как видно из примера кода, я получаю разные сообщения об ошибках, особенно в первом примере, который меня сбивает с толку, поскольку TemporalAccessor содержит год на основе недели, неделю года и день недели, чего должно быть достаточно для создания LocalDate .
Exception in thread "main" java.time.format.DateTimeParseException: Text '201901' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {WeekOfYear[WeekFields[MONDAY,4]]=1, WeekBasedYear[WeekFields[MONDAY,4]]=2019, DayOfWeek=7},ISO of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1931)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1866)
at java.time.LocalDate.parse(LocalDate.java:411)
at Main.formatter1(Main.java:22)
at Main.main(Main.java:10)
Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {WeekOfYear[WeekFields[MONDAY,4]]=1, WeekBasedYear[WeekFields[MONDAY,4]]=2019, DayOfWeek=7},ISO of type java.time.format.Parsed
at java.time.LocalDate.from(LocalDate.java:379)
at java.time.LocalDate$$Lambda$7.000000001061ED20.queryFrom(Unknown Source)
at java.time.format.Parsed.query(Parsed.java:237)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1862)
... 3 more
TemporalAccessor a = formatter.parse("...");
таким образом, вы получаете промежуточный шаг, и немного проще понять, почему все происходит именно так, как происходит :) - person Rohde Fischer   schedule 13.08.2019formatter2
иformatter3
безупречно работают на моей Java 11. Чтобы заставитьformatter1
работать, просто заменитеWeekFields.ISO.weekOfYear()
наWeekFields.ISO.weekOfWeekBasedYear()
- person Ole V.V.   schedule 21.08.2019formatter2()
бросаетjava.time.format.DateTimeParseException: Text '201901' could not be parsed at index 0
.formatter3()
вместо этого выдаетjava.time.format.DateTimeParseException: Text '201901' could not be parsed at index 6
. Я нахожу это очень интересным и не могу сразу объяснить. (Добавление вашей версии Java в вопрос позволит мне отозвать свой отрицательный голос.) - person Ole V.V.   schedule 26.08.2019