【发布时间】:2018-06-24 06:36:51
【问题描述】:
我正在尝试从没有任何分隔符的字符串中解析基于周的年份和基于周的年份。例如。 “201812”(2018 年第 12 周)。像这样:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("YYYYww")
.parseDefaulting(WeekFields.ISO.dayOfWeek(), 1)
.toFormatter();
LocalDate parse = LocalDate.parse("201803", formatter);
但这给了我:
java.time.format.DateTimeParseException: Text '201803' could not be parsed at index 0
如果我像这样在字段之间添加一个空格:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("YYYY ww")
.parseDefaulting(WeekFields.ISO.dayOfWeek(), 1)
.toFormatter();
LocalDate parse = LocalDate.parse("2018 03", formatter);
效果很好,结果:
2018-01-15
Is this another bug like this one?或者我错过了什么?
我发现的解决方法是构建自定义格式化程序:
DateTimeFormatter yearWeekPattern = new DateTimeFormatterBuilder().appendValue(IsoFields.WEEK_BASED_YEAR, 4)
.appendValue(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 2)
.parseDefaulting(WeekFields.ISO.dayOfWeek(), 1)
.toFormatter();
LocalDate.parse("201803", yearWeekPattern).atStartOfDay(ZoneId.systemDefault()).toInstant();
【问题讨论】: