3

The kind of String I want to parse : "36/2017", with 36 the week of the year, 2017 the year.

My code :

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

I added a default day.

I have this message :

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

Any idea ? Thank you !

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
FloFlow
  • 121
  • 1
  • 8
  • Please provide the stacktrace if possible (you should do this with any exception you're asking about). – Thomas Aug 29 '19 at 15:08
  • Tip: Teach the publisher of your input data about the standard [ISO 8601 week date](https://en.wikipedia.org/wiki/ISO_week_date) formats: `2017-W36` – Basil Bourque Aug 29 '19 at 17:48
  • Tip: [`YearWeek`](https://www.threeten.org/threeten-extra/apidocs/org.threeten.extra/org/threeten/extra/YearWeek.html) class in the *[ThreeTen-Extra*](https://www.threeten.org/threeten-extra/) project. – Basil Bourque Aug 29 '19 at 17:51

2 Answers2

5

From the docs: https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

You should use uppercase Y's if you are using weeks.

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);
}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Katie.Sun
  • 711
  • 3
  • 15
4

The pattern is wrong. You must set the following string

"w/YYYY"

DateTimeFormatter formatter = new 
DateTimeFormatterBuilder()
                .appendPattern("w/YYYY")
                .parseDefaulting(ChronoField.DAY_OF_WEEK, 1)
                .toFormatter();
LocalDate date = LocalDate.parse("36/2017", formatter);
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
ynsanity
  • 53
  • 6