将具有星期和年份的字符串解析为LocalDate

Flo*_*low 3 java date java-time

我要解析的字符串类型:“ 36/2017”,其中36个是一年中的第一个星期,2017年是该年。

我的代码:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                    .appendPattern("w/uuuu")
                    .parseDefaulting(ChronoField.DAY_OF_WEEK, 1)
                    .toFormatter();
LocalDate date = LocalDate.parse("36/2017", formatter);
Run Code Online (Sandbox Code Playgroud)

我添加了默认日期。

我收到此消息:

java.time.format.DateTimeParseException: Text '36/2017' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {WeekOfWeekBasedYear[WeekFields[MONDAY,4]]=36, Year=2017, DayOfWeek=1},ISO of type java.time.format.Parsed
Run Code Online (Sandbox Code Playgroud)

任何的想法 ?谢谢 !

小智 5

从文档中:https : //docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

如果要使用星期,则应使用大写的Y。

public static void main(String[] args) {
    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .appendPattern("w/YYYY")
            .parseDefaulting(ChronoField.DAY_OF_WEEK, 1)
            .toFormatter();
    LocalDate date = LocalDate.parse("36/2017", formatter);
}
Run Code Online (Sandbox Code Playgroud)