Java 8 Date API - Getting week of month throws UnsupportedTemporalTypeException: Unsupported field: DayOfWeek

Viewed 1150

I am trying to get the week of the current month like so:

YearMonth
    .from(Instant.now().atZone(ZoneId.of("UTC")))
    .get(WeekFields.ISO.weekOfMonth())

But this throws

java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: DayOfWeek

I can't seem to work out why I'm getting this exception, because I'm not doing anything with DayOfWeek. Any ideas?

1 Answers

You can't get the week of the current month using YearMonth. It only has year and month. Change

YearMonth
    .from(Instant.now().atZone(ZoneId.of("UTC")))
    .get(WeekFields.ISO.weekOfMonth())

to

LocalDate
    .from(Instant.now().atZone(ZoneId.of("UTC")))
    .get(WeekFields.ISO.weekOfMonth())

And I get

1
Related